题解
迭代版本
一共三个指针,一个是记录最开始的节点,一个是当前反转节点,一个是下一个待反转的节点。
记住这里是反转,所以,针对节点来看,将当前节点 cur 指向最开始节点,即完成反转。
然后所有指针往下走一步。
走的顺序是从前往后走,即最开始节点=当前反转节点,当前反转节点=下一个待反转节点。
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* cur, * nxt;
cur = head;
while(cur){
nxt = cur->next;
cur->next = prev;
prve = cur;
cur = nxt;
}
return prev;
}
};
反转链表 ACM 版本
加了输入输出以及相对应的初始化部分,更方便调试一些。
cpp
#include <iostream>
#include <list>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {};
ListNode(int x) : val(x), next(nullptr) {};
ListNode(int x, ListNode *next) : val(x), next(next) {};
};
class Solution
{
public:
ListNode *reverseList(ListNode *head)
{
ListNode *prev = nullptr;
ListNode *cur, *nxt;
cur = head;
while (cur)
{
nxt = cur->next;
cur->next = prev;
prev = cur;
cur = nxt;
}
return prev;
}
};
int main()
{
ListNode *head = nullptr, *tail = nullptr;
int x, n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> x;
ListNode *tmp = new ListNode(x, nullptr);
if (head == nullptr)
{
head = tail = tmp;
}
else
{
tail->next = tmp;
tail = tmp;
}
cout << x << endl;
}
Solution solution;
head = solution.reverseList(head);
while (head)
{
cout << head->val << " ";
head = head->next;
}
return 0;
}