用c语言在一个代码中分步实现:(1)实现单链表的创建;(2)实现单链表的插入;(3)实现单链表的删除 (4)实现单链表的查找;(5)实现单链表的显示;
时间: 2023-05-31 12:02:48 浏览: 111
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
typedef struct ListNode {
int val; // 节点数据
struct ListNode *next; // 指向下一个节点的指针
} ListNode;
// 创建单链表
ListNode* createList() {
ListNode *head = NULL; // 头节点
ListNode *tail = NULL; // 尾节点
int val;
printf("请输入节点值,输入-1结束:\n");
while (1) {
scanf("%d", &val);
if (val == -1) {
break;
}
ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->val = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 插入节点
void insertNode(ListNode *head, int pos, int val) {
ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->val = val;
newNode->next = NULL;
if (pos == 1) {
newNode->next = head;
head = newNode;
} else {
ListNode *cur = head;
for (int i = 1; i < pos - 1; i++) {
cur = cur->next;
if (cur == NULL) {
printf("插入位置无效!\n");
return;
}
}
newNode->next = cur->next;
cur->next = newNode;
}
}
// 删除节点
void deleteNode(ListNode *head, int val) {
ListNode *cur = head;
ListNode *pre = NULL;
while (cur != NULL) {
if (cur->val == val) {
if (pre == NULL) {
head = cur->next;
} else {
pre->next = cur->next;
}
free(cur);
return;
}
pre = cur;
cur = cur->next;
}
printf("未找到节点!\n");
}
// 查找节点
ListNode* findNode(ListNode *head, int val) {
ListNode *cur = head;
while (cur != NULL) {
if (cur->val == val) {
return cur;
}
cur = cur->next;
}
printf("未找到节点!\n");
return NULL;
}
// 显示单链表
void displayList(ListNode *head) {
ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
ListNode *head = createList();
printf("创建的单链表为:");
displayList(head);
printf("请输入要插入的节点位置和值:");
int pos, val;
scanf("%d %d", &pos, &val);
insertNode(head, pos, val);
printf("插入节点后的单链表为:");
displayList(head);
printf("请输入要删除的节点的值:");
scanf("%d", &val);
deleteNode(head, val);
printf("删除节点后的单链表为:");
displayList(head);
printf("请输入要查找的节点的值:");
scanf("%d", &val);
ListNode *node = findNode(head, val);
if (node != NULL) {
printf("找到了节点,值为%d\n", node->val);
}
return 0;
}
阅读全文