题目描述:
题号:206
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
解题思路:
思路一:双指针迭代
算法思路:
在遍历链表时,将当前节点的 next 指针改为指向前一个节点。
因此需要:1、储存当前节点的前一个节点 2、储存当前节点的后一个节点
时间复杂度:O(N)
空间复杂度:O(1)
C++
// C++
/**
* 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 *cur = head, *pre = nullptr;
while(cur != nullptr) {
ListNode *temp = cur->next;
// 使当前节点指向前一个节点
cur->next = pre;
// 准备处理下一个节点
// 两指针都向前移动一个元素
pre = cur;
cur = temp;
}
return pre;
}
};
go
// go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
var pre *ListNode
cur := head
for cur != nil {
temp := cur.Next
// 使当前指针指向它的前一个节点
cur.Next = pre
// 两指针都向前移动一个元素
pre = cur
cur = temp
}
return pre
}
思路二:递归
思路关键点:假设后面的链表都已经反转完成了,该如何翻转当前节点?(函数调用栈是先进后出的,因此是链表的后半部分先被反转)
解决思路:假设当前节点是 2
原链表:1 -> 2 -> 3 -> 4 -> 5
当前函数递归的链表:1 -> 2 -> 3 <- 4 <- 5
需要节点 3 的 next 指针指向 2,即 3 -> next 指向 2,即 2 -> next -> next 指向 2 ( 3 是 2 的 next )
时间复杂度:O(N)
空间复杂度:O(1)
C++
// C++
/**
* 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* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
go
// go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
// 递归结束条件
if head == nil || head.Next == nil {
return head
}
newHead := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return newHead
}