c语言编程实现单向链表建立、删除、插入、输出
时间: 2023-10-10 12:13:21 浏览: 80
C语言实现单向链表的创建、插入,删除节点,和2个链表合并
5星 · 资源好评率100%
以下是基于C语言实现的单向链表建立、删除、插入、输出的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
//定义链表节点结构体
typedef struct Node {
int data; //数据
struct Node *next; //指向下一个节点的指针
} Node;
//创建新节点并返回指针
Node* createNode(int data) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
//在链表尾部插入节点
void insertAtEnd(Node **head, int data) {
Node *newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
//在链表头部插入节点
void insertAtBeginning(Node **head, int data) {
Node *newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
//在链表中间插入节点
void insertAtPosition(Node **head, int data, int position) {
Node *newNode = createNode(data);
if (position == 1) {
newNode->next = *head;
*head = newNode;
} else {
Node *temp = *head;
for (int i = 1; i < position - 1; i++) {
temp = temp->next;
if (temp == NULL) {
printf("Invalid position\n");
return;
}
}
newNode->next = temp->next;
temp->next = newNode;
}
}
//从链表中删除节点
void deleteNode(Node **head, int data) {
Node *temp = *head;
Node *prev = NULL;
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Node not found\n");
return;
}
if (prev == NULL) {
*head = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
}
//输出链表
void printList(Node *head) {
Node *temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
Node *head = NULL;
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtBeginning(&head, 0);
insertAtPosition(&head, 4, 4);
deleteNode(&head, 2);
printList(head);
return 0;
}
```
运行结果:
```
0 -> 1 -> 4 -> 3 -> NULL
```
以上代码实现了单向链表的基本操作,可以根据需要进行修改和扩展。
阅读全文