Leetcode 206 反转链表
一、题目
给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
二、解法
方法一
人最容易想到的是递归解法。
先使用 reverseList(head->next) 递归地处理该链表,效果是将从head->next的结点到最后一个结点翻转。
记录下head->next结点的位置,并且断开head和head->next结点的指针域连接,再把head结点放到翻转后的链表的末尾。
/**
* 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) {
if(head==nullptr || head->next==nullptr) return head;
ListNode* p=head->next,*q=reverseList(head->next);
head->next=nullptr;
p->next=head;
return q;
}
};
方法二
设置pre、cur、next三个指针。cur指向当前结点,pre指向当前结点的前一个结点,next指向当前结点的后一个结点。
从头到尾遍历一遍链表,每次让cur的指针域指向前一个结点,同时更新pre、cur和next指针的值。
/**
* 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) {
if(head==nullptr || head->next==nullptr) return head;
ListNode* pre=nullptr,*cur=head,*next=cur->next;
while(cur){
cur->next=pre;
pre=cur;
cur=next;
if(cur) next=cur->next;
}
return pre;
}
};