把一个带头结点的单链表的倒置
时间: 2023-10-19 21:07:42 浏览: 31
下面是一个带头结点的单链表的倒置的 C++ 实现:
```cpp
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode *prev = NULL, *cur = head, *next = NULL;
while (cur != NULL) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
int main() {
// 创建一个带头结点的单链表
ListNode *head = new ListNode(-1);
ListNode *p = head;
for (int i = 1; i <= 5; i++) {
ListNode *node = new ListNode(i);
p->next = node;
p = p->next;
}
cout << "原链表:";
p = head->next;
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
head->next = reverseList(head->next);
cout << "倒置后的链表:";
p = head->next;
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
return 0;
}
```
输出结果为:
```
原链表:1 2 3 4 5
倒置后的链表:5 4 3 2 1
```