数据结构c语言单链表的创建输出查找删除插入及主函数功能菜单
时间: 2023-04-28 18:01:28 浏览: 148
单链表是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。在C语言中,可以通过结构体来实现单链表。
以下是单链表的创建、输出、查找、删除、插入以及主函数功能菜单的示例代码:
//定义单链表节点结构体
typedef struct Node{
int data; //数据元素
struct Node *next; //指向下一个节点的指针
}Node;
//创建单链表
Node* createList(){
Node *head, *p, *q;
int n, i;
head = (Node*)malloc(sizeof(Node)); //创建头节点
head->next = NULL;
q = head;
printf("请输入节点个数:");
scanf("%d", &n);
for(i=0; i<n; i++){
p = (Node*)malloc(sizeof(Node)); //创建新节点
printf("请输入第%d个节点的值:", i+1);
scanf("%d", &p->data);
p->next = NULL;
q->next = p; //将新节点插入到链表尾部
q = p;
}
return head;
}
//输出单链表
void printList(Node *head){
Node *p = head->next;
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
//查找节点
Node* findNode(Node *head, int x){
Node *p = head->next;
while(p != NULL && p->data != x){
p = p->next;
}
return p;
}
//删除节点
void deleteNode(Node *head, int x){
Node *p = head->next, *q = head;
while(p != NULL && p->data != x){
q = p;
p = p->next;
}
if(p != NULL){
q->next = p->next;
free(p);
}
}
//插入节点
void insertNode(Node *head, int x, int pos){
Node *p = head->next, *q = head;
int i = 1;
while(p != NULL && i < pos){
q = p;
p = p->next;
i++;
}
if(i == pos){
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = p;
q->next = newNode;
}
}
//主函数功能菜单
int main(){
Node *head = NULL;
int choice, x, pos;
while(1){
printf("1.创建单链表\n");
printf("2.输出单链表\n");
printf("3.查找节点\n");
printf("4.删除节点\n");
printf("5.插入节点\n");
printf("6.退出程序\n");
printf("请输入您的选择:");
scanf("%d", &choice);
switch(choice){
case 1:
head = createList();
break;
case 2:
printList(head);
break;
case 3:
printf("请输入要查找的节点的值:");
scanf("%d", &x);
if(findNode(head, x) != NULL){
printf("节点已找到!\n");
}else{
printf("节点未找到!\n");
}
break;
case 4:
printf("请输入要删除的节点的值:");
scanf("%d", &x);
deleteNode(head, x);
break;
case 5:
printf("请输入要插入的节点的值和位置:");
scanf("%d %d", &x, &pos);
insertNode(head, x, pos);
break;
case 6:
exit(0);
default:
printf("输入有误,请重新输入!\n");
break;
}
}
return 0;
}
阅读全文