C语言编程实现单链表的创建、插入和删除。然后输出顺序表的内容。元素由用户从键盘输入。
时间: 2023-08-20 07:05:03 浏览: 84
下面是C语言实现单链表的创建、插入和删除的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
// 创建新的链表节点
ListNode *createNode(int val) {
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 向链表末尾插入新节点
void insertNode(ListNode **head, int val) {
ListNode *node = createNode(val);
if (*head == NULL) {
*head = node;
} else {
ListNode *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = node;
}
}
// 删除链表中值为 val 的节点
void deleteNode(ListNode **head, int val) {
ListNode *prev = NULL;
ListNode *curr = *head;
while (curr != NULL && curr->val != val) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) {
printf("Node with value %d not found\n", val);
} else if (prev == NULL) {
*head = curr->next;
free(curr);
} else {
prev->next = curr->next;
free(curr);
}
}
// 输出链表内容
void printList(ListNode *head) {
printf("List: ");
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
ListNode *head = NULL;
int num, val;
printf("Enter the number of elements: ");
scanf("%d", &num);
for (int i = 0; i < num; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &val);
insertNode(&head, val);
}
printList(head);
printf("Enter the value to delete: ");
scanf("%d", &val);
deleteNode(&head, val);
printList(head);
return 0;
}
```
上述代码中,我们首先定义了一个单链表节点结构体 `ListNode`,它包含一个整数值和一个指向下一个节点的指针。然后我们定义了三个函数来实现单链表的创建、插入和删除操作。
在 `createNode` 函数中,我们使用 `malloc` 动态分配内存来创建新的节点,并将节点的值和指针初始化为给定的值和 `NULL`。
在 `insertNode` 函数中,我们首先创建一个新节点,然后遍历链表直到末尾,并在末尾插入新节点。
在 `deleteNode` 函数中,我们遍历链表直到找到值为 `val` 的节点,然后将其从链表中删除。
最后,我们使用 `printList` 函数输出链表的内容。在 `main` 函数中,我们首先从用户输入中读取链表元素的数量和值,并使用 `insertNode` 函数向链表中插入新节点。然后,我们使用 `deleteNode` 函数删除链表中给定值的节点,并最终使用 `printList` 函数输出链表内容。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)