pta6-1 单链表逆转
时间: 2023-10-29 11:05:34 浏览: 117
好的,pta6-1 单链表逆转是一道经典的链表题目,其主要思路是通过遍历链表,将每个节点的 next 指针指向其前驱节点,最终将整个链表逆序。具体实现可以参考以下代码:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseList(ListNode* head) {
ListNode *prev = NULL, *curr = head;
while (curr != NULL) {
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
ListNode *head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
ListNode *newHead = reverseList(head);
while (newHead != NULL) {
cout << newHead->val << " ";
newHead = newHead->next;
}
cout << endl;
return 0;
}
```
阅读全文