编程实现单向链表建立、删除、插入、输出c
时间: 2023-10-07 16:09:26 浏览: 72
以下是单向链表的基本实现,包括建立、删除、插入、输出等操作。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct node {
int data; // 数据域
struct node *next; // 指针域,指向下一个节点
} Node;
// 创建新节点
Node* newNode(int data) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = data;
p->next = NULL;
return p;
}
// 在链表末尾插入新节点
Node* insertAtTail(Node *head, int data) {
Node *p = newNode(data);
if (head == NULL) {
head = p;
} else {
Node *q = head;
while (q->next != NULL) {
q = q->next;
}
q->next = p;
}
return head;
}
// 在链表头部插入新节点
Node* insertAtHead(Node *head, int data) {
Node *p = newNode(data);
if (head == NULL) {
head = p;
} else {
p->next = head;
head = p;
}
return head;
}
// 在链表中间插入新节点(在第k个节点之后插入)
Node* insertAfterKth(Node *head, int k, int data) {
Node *p = newNode(data);
if (head == NULL) {
head = p;
} else {
Node *q = head;
int i = 0;
while (q != NULL && i < k) {
q = q->next;
i++;
}
if (q != NULL) { // 找到第k个节点
p->next = q->next;
q->next = p;
}
}
return head;
}
// 删除第k个节点
Node* deleteKth(Node *head, int k) {
if (head == NULL) {
return NULL;
}
if (k == 1) { // 删除头节点
Node *p = head;
head = head->next;
free(p);
} else {
Node *p = head, *q = head->next;
int i = 2;
while (q != NULL && i < k) {
p = q;
q = q->next;
i++;
}
if (q != NULL) { // 找到第k个节点
p->next = q->next;
free(q);
}
}
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 = NULL;
head = insertAtTail(head, 1);
head = insertAtTail(head, 2);
head = insertAtHead(head, 0);
head = insertAfterKth(head, 2, 3);
printList(head);
head = deleteKth(head, 3);
printList(head);
head = deleteKth(head, 1);
printList(head);
return 0;
}
```
在主函数中,首先创建一个空链表 `head`。然后依次调用 `insertAtTail()`、`insertAtHead()`、`insertAfterKth()` 将元素插入链表中,再调用 `printList()` 输出链表。接着调用 `deleteKth()` 删除第k个节点,再输出链表。最后再次调用 `deleteKth()` 删除头节点,最终输出链表。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)