单链表的就地反转,包括新建单链表,依次输出单链表节点值,就地反转,摧毁单链表四个算法,用c语言编写
时间: 2024-10-14 09:07:47 浏览: 18
单链表的就地反转
单链表的就地反转是指在不创建新链表的情况下,改变原链表的结构使其头结点变成最后一个节点的过程。下面是使用C语言实现这四个步骤的一个简要概述:
1. 新建单链表(Create a linked list):
```c
struct Node {
int data;
struct Node* next;
};
void insert(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = head;
head = newNode;
}
```
2. 依次输出单链表节点值(Print the list):
```c
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
```
3. 就地反转单链表(In-place reverse):
```c
void reverseList(struct Node** head) {
struct Node *prev = NULL, *current = *head, *next;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
```
4. 摧毁单链表(Destroy the list):
```c
void destroyList(struct Node** head) {
struct Node* temp;
while (*head != NULL) {
temp = *head;
*head = (*head)->next;
free(temp);
}
}
```
以上函数假设`head`指向链表的头节点。注意,在实际使用中,你需要确保有足够的内存分配,并正确处理可能的边界情况。
阅读全文