C语言假设线性表(a1,a2,a3,…an)采用带头结点的单链表存储,请设计算法函数将带头结点的单链表head就地倒置,使表变成(an,an-1,…a3.a2,a1)。并构造测试用例进行测试
时间: 2023-06-12 08:03:02 浏览: 127
方法顺序建立带头结点的单链表-线性表讲解PPT
下面是C语言的算法函数实现:
```c
void reverseList(Node* head) {
if (head == NULL || head->next == NULL) {
return;
}
Node* prev = NULL;
Node* curr = head->next;
Node* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head->next = prev;
}
```
其中,Node为单链表的节点类型,包含一个数据域和一个指向下一个节点的指针域。head为带头结点的单链表的头指针。
算法的实现思路是采用三个指针prev、curr和next,初始时prev为NULL,curr为头结点的下一个节点,next为NULL。然后每次将curr节点的next指针指向prev,然后将prev指针移动到curr所在的位置,将curr指针移动到next所在的位置,继续循环直到curr为NULL。最后将头结点的next指针指向prev即可。
以下是测试用例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void reverseList(Node* head) {
if (head == NULL || head->next == NULL) {
return;
}
Node* prev = NULL;
Node* curr = head->next;
Node* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head->next = prev;
}
void printList(Node* head) {
if (head == NULL || head->next == NULL) {
printf("List is empty.\n");
return;
}
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void test() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
int n = 5;
for (int i = 1; i <= n; i++) {
Node* p = (Node*)malloc(sizeof(Node));
p->data = i;
p->next = head->next;
head->next = p;
}
printf("原始链表:");
printList(head);
reverseList(head);
printf("反转链表:");
printList(head);
}
int main() {
test();
return 0;
}
```
输出结果:
```
原始链表:1 2 3 4 5
反转链表:5 4 3 2 1
```
阅读全文