206. 反轉鏈表 - 力扣(LeetCode)
題解
迭代版本
一共三個指針,一個是記錄最開始的節點,一個是當前反轉節點,一個是下一個待反轉的節點。
記住這里是反轉,所以,針對節點來看,將當前節點 cur 指向最開始節點,即完成反轉。
然后所有指針往下走一步。
走的順序是從前往后走,即最開始節點=當前反轉節點,當前反轉節點=下一個待反轉節點。
/*** 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 版本
加了輸入輸出以及相對應的初始化部分,更方便調試一些。
#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;
}