题目来源:反转链表
在bilibili上的视频讲解:https://www.bilibili.com/video/BV1ei4y1Y7yF/
题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是 [0, 5000]
- -5000 <= Node.val <= 5000
解题思路
思路步骤
step1:定义fast、slow、pre三个指针,fast、slow指向头节点,pre指向空地址
fast指针:表示需要反转链表的头节点的下一个节点
slow指针:表示需要反转链表的头节点
pre指针:表示反转后链表的头节点
step2:
-
fast指向头节点的下一个节点
-
slow节点的next指向pre
-
pre指向slow
-
slow指向fast
step3:重复step2步骤,直到fast为空,返回pre
思路动画
代码
Python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
pre = None
while fast:
fast = fast.next
slow.next = pre
pre = slow
slow = fast
return pre
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) {
ListNode* fast = head;
ListNode* slow = head;
ListNode* pre = nullptr;
while (fast != nullptr) {
fast = fast->next;
slow->next = pre;
pre = slow;
slow = fast;
}
return pre;
}
};
Java代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode fast = head;
ListNode slow = head;
ListNode pre = null;
while (fast != null) {
fast = fast.next;
slow.next = pre;
pre = slow;
slow = fast;
}
return pre;
}
}