编写算法逆置一个带头结点的双链表代码c++
时间: 2024-04-06 21:11:22 浏览: 114
以下是逆置一个带头结点的双链表的C++代码:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode* prev;
ListNode(int x) : val(x), next(NULL), prev(NULL) {}
};
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* curr = head->next;
ListNode* prev = NULL;
while (curr != NULL) {
ListNode* next = curr->next;
curr->next = prev;
curr->prev = next;
prev = curr;
curr = next;
}
head->next = prev;
head->next->prev = NULL;
return head;
}
int main() {
ListNode* head = new ListNode(-1);
ListNode* tail = head;
for (int i = 1; i <= 5; i++) {
ListNode* node = new ListNode(i);
tail->next = node;
node->prev = tail;
tail = node;
}
cout << "Original list: ";
ListNode* curr = head->next;
while (curr != NULL) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
head = reverseList(head);
cout << "Reversed list: ";
curr = head->next;
while (curr != NULL) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
return 0;
}
```
这里使用了双指针法,通过一个 `prev` 指针和一个 `curr` 指针来逆置链表。同时需要注意一些细节,比如链表头结点的处理和指针的赋值顺序等。
阅读全文