用c语言实现线性表的链式存储实现 单链表的插入、删除、查找、求表长、置逆以及有序单链表的合并算法的实现。
时间: 2024-09-27 22:05:16 浏览: 48
在C语言中,我们可以使用结构体(struct)来表示链表节点,并通过指针(pointer)链接节点,实现线性表的链式存储。这里简单地概述一些基本操作的实现:
1. **节点结构体定义**:
```c
typedef struct Node {
int data; // 数据域
struct Node* next; // 指向下一个节点的指针
} Node;
```
2. **创建链表头结点**:
```c
Node* createList() {
return (Node*)malloc(sizeof(Node)); // 分配内存并初始化为头结点
}
```
3. **插入操作**(例如在头部插入):
```c
void insertAtStart(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
4. **删除操作**(例如删除头部元素):
```c
void deleteFromStart(Node** head) {
if (*head == NULL) return;
Node* temp = *head;
*head = (*head)->next;
free(temp);
}
```
5. **查找操作**:
```c
Node* search(Node* head, int key) {
Node* current = head;
while (current != NULL && current->data != key) {
current = current->next;
}
return current;
}
```
6. **求表长**:
```c
int getLength(Node* head) {
int count = 0;
Node* temp = head;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
```
7. **置逆链表**(翻转链表):
```c
void reverseList(Node** head) {
Node* prev = NULL;
Node* current = *head;
Node* next暂存;
while (current != NULL) {
next暂存 = current->next;
current->next = prev;
prev = current;
current = next暂存;
}
*head = prev;
}
```
8. **合并两个有序链表**:
```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;
}
}
```
阅读全文