假设线性表(a1,a2…a3)采用带头结点的单链表储存,请设计计算法函数void reverse(linklist head),将带头结点的单链表head倒置,使表变成(a3…a2,a1)并构造测试用例进行测试
时间: 2024-06-12 16:11:51 浏览: 144
可以通过遍历链表,将每个节点的指针指向其前驱节点来实现链表的倒置。具体实现如下:
```c++
typedef struct Node {
int data;
struct Node* next;
} ListNode, *LinkList;
void reverse(LinkList head) {
if (head == NULL || head->next == NULL) {
return;
}
ListNode* prev = NULL;
ListNode* curr = head->next;
ListNode* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head->next = prev;
}
```
测试用例可以构造如下:
```c++
int main() {
LinkList head = new ListNode();
head->next = NULL;
for (int i = 1; i <= 3; i++) {
ListNode* node = new ListNode();
node->data = i;
node->next = head->next;
head->next = node;
}
reverse(head);
ListNode* curr = head->next;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
return 0;
}
```
输出结果为:3 2 1
阅读全文