单链表创建、删除、查找、插入、主函数c语言代码
时间: 2023-07-10 22:14:25 浏览: 33
以下是单链表的完整C语言代码,包括创建、删除、查找、插入和主函数:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList() {
Node *head = NULL;
Node *tail = NULL;
int num;
printf("请输入链表的数据,以-1结束:");
scanf("%d", &num);
while (num != -1) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = num;
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
} else {
tail->next = p;
tail = p;
}
scanf("%d", &num);
}
return head;
}
Node *deleteNode(Node *head, int num) {
Node *p = head;
Node *prev = NULL;
while (p != NULL && p->data != num) {
prev = p;
p = p->next;
}
if (p == NULL) {
printf("链表中没有该结点\n");
return head;
}
if (prev == NULL) {
head = head->next;
} else {
prev->next = p->next;
}
free(p);
return head;
}
Node *searchNode(Node *head, int num) {
Node *p = head;
while (p != NULL && p->data != num) {
p = p->next;
}
if (p == NULL) {
printf("链表中没有该结点\n");
return NULL;
}
return p;
}
Node *insertNode(Node *head, int num, int index) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = num;
p->next = NULL;
if (head == NULL) {
if (index == 0) {
return p;
} else {
printf("链表为空,不能插入结点\n");
free(p);
return NULL;
}
}
if (index == 0) {
p->next = head;
return p;
}
Node *prev = head;
Node *next = head->next;
int i = 1;
while (next != NULL && i != index) {
prev = prev->next;
next = next->next;
i++;
}
if (i != index) {
printf("插入位置超出链表长度\n");
free(p);
return head;
}
prev->next = p;
p->next = next;
return head;
}
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = createList();
printList(head);
head = deleteNode(head, 3);
printList(head);
Node *p = searchNode(head, 2);
if (p != NULL) {
printf("查找到结点:%d\n", p->data);
}
head = insertNode(head, 5, 2);
printList(head);
return 0;
}
```