C语言实现线性单链表的定义、初始化、插入、删除及数据的显示、求长度、逆置以及两个有序单链表的合并
时间: 2024-10-24 12:15:16 浏览: 38
(数据结构C语言版)顺序表和单链表的逆置.pdf
在C语言中,线性单链表是一种基础的数据结构,它由节点组成,每个节点包含一个数据域和一个指向下一个节点的指针。下面是定义、初始化、操作和合并的一个简要概述:
**定义与初始化:**
```c
// 定义链表节点结构体
typedef struct Node {
int data; // 数据域
struct Node* next; // 指向下一个节点的指针
} Node;
// 初始化空链表
Node* createList() {
return NULL;
}
```
**插入操作:**
- 插入到头部 (`push`):
```c
void push(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
- 插入到尾部 (`append`):
```c
void append(Node** head, int value) {
if (*head == NULL) {
push(head, value);
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = (Node*)malloc(sizeof(Node));
current->next->data = value;
current->next->next = NULL;
}
}
```
**删除操作:**
- 删除首节点 (`deleteFirst`):
```c
void deleteFirst(Node** head) {
if (*head != NULL) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
}
}
```
- 删除指定值的节点 (`deleteByValue`):
```c
void deleteByValue(Node** head, int value) {
if (*head != NULL && (*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
} else {
Node* current = *head;
while (current->next != NULL && current->next->data != value) {
current = current->next;
}
if (current->next != NULL) {
Node* toDelete = current->next;
current->next = current->next->next;
free(toDelete);
}
}
}
```
**数据显示:**
```c
void display(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
**求链表长度:**
```c
int length(Node* head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
```
**逆置链表:**
```c
void reverse(Node** head) {
Node* prev = NULL;
Node* current = *head;
Node* nextTemp;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
*head = prev;
}
```
**合并两个有序链表:**
```c
Node* mergeSortedLists(Node* list1, Node* list2) {
if (list1 == NULL) return list2;
if (list2 == NULL) return list1;
if (list1->data < list2->data) {
list1->next = mergeSortedLists(list1->next, list2);
return list1;
} else {
list2->next = mergeSortedLists(list1, list2->next);
return list2;
}
}
```
阅读全文