C++编程实现一个对单链表进行基本操作的系统,主要包括表的创建,输入,查询,取值,插入,删除,输出等操作
时间: 2024-05-21 13:10:47 浏览: 11
#include <stdio.h>
#include <stdlib.h>
//定义单链表结构体
typedef struct Node{
int data;
struct Node* next;
}Node;
//创建一个单链表
Node* createList(int n){
Node* head = NULL;
Node* tail = NULL;
for(int i=0; i<n; i++){
Node* newNode = (Node*)malloc(sizeof(Node));
printf("请输入第%d个节点的值:", i+1);
scanf("%d", &(newNode->data));
newNode->next = NULL;
if(head == NULL){
head = newNode;
tail = newNode;
}else{
tail->next = newNode;
tail = newNode;
}
}
printf("创建成功!\n");
return head;
}
//输出单链表
void printList(Node* head){
if(head == NULL){
printf("链表为空!\n");
return;
}
Node* p = head;
while(p){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
//查询节点是否存在
Node* searchNode(Node* head, int x){
Node* p = head;
while(p && p->data != x){
p = p->next;
}
return p;
}
//获取节点的值
int getValue(Node* head, int pos){
if(head == NULL){
printf("链表为空!\n");
return -1;
}
Node* p = head;
int i = 0;
while(p && i<pos){
p = p->next;
i++;
}
if(p == NULL || i>pos){
printf("位置错误!\n");
return -1;
}
return p->data;
}
//在指定位置插入节点
Node* insertNode(Node* head, int pos, int x){
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;
if(head == NULL){
head = newNode;
return head;
}
if(pos == 0){
newNode->next = head;
head = newNode;
return head;
}
Node* p = head;
int i = 0;
while(p && i<pos-1){
p = p->next;
i++;
}
if(p == NULL || i>pos-1){
printf("位置错误!\n");
return head;
}
newNode->next = p->next;
p->next = newNode;
printf("插入成功!\n");
return head;
}
//删除指定位置的节点
Node* deleteNode(Node* head, int pos){
if(head == NULL){
printf("链表为空!\n");
return head;
}
if(pos == 0){
Node* p = head;
head = head->next;
free(p);
printf("删除成功!\n");
return head;
}
Node* p = head;
int i = 0;
while(p && i<pos-1){
p = p->next;
i++;
}
if(p == NULL || p->next == NULL || i>pos-1){
printf("位置错误!\n");
return head;
}
Node* q = p->next;
p->next = q->next;
free(q);
printf("删除成功!\n");
return head;
}
int main(){
int n;
printf("请输入单链表的长度:");
scanf("%d", &n);
Node* head = createList(n);
printList(head);
int x;
printf("请输入要查询的节点值:");
scanf("%d", &x);
Node* p = searchNode(head, x);
if(p == NULL){
printf("该节点不存在!\n");
}else{
printf("该节点存在!\n");
}
int pos;
printf("请输入要获取值的节点位置:");
scanf("%d", &pos);
int value = getValue(head, pos);
if(value != -1){
printf("该节点的值为:%d\n", value);
}
int insertPos;
printf("请输入要插入的位置:");
scanf("%d", &insertPos);
printf("请输入要插入的节点值:");
scanf("%d", &x);
head = insertNode(head, insertPos, x);
printList(head);
int deletePos;
printf("请输入要删除的位置:");
scanf("%d", &deletePos);
head = deleteNode(head, deletePos);
printList(head);
return 0;
}