leetcode刷题系列----模式2(Datastructure 链表)- 206:Reverse Linked List 反转链表
Tips
- 更多题解请见本系列目录
- 此题使用迭代法可以解决。
- 首先定义current和previous两个指针。
- 使用head保存current的next节点。
- 断开current和current的next之间的链。
- 建立current和current的next之间新链接,current的next改为指向previous。
- previous被释放,将current变为previous,head赋值current。
- 开启新一轮迭代,思想似乎还有双指针的影子。
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: ListNode) -> ListNode:
current = head
previous = None
while current:
temp = current.next
current.next = previous
previous = current
current = temp
return previous
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* current = head;
ListNode* previous = nullptr;
// 此时head已经无用,使用head作为缓存
while(current!=nullptr)
{
head = current->next;
current->next = previous;
previous = current;
current = head;
}
return previous;
}
};
C#
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode current = head;
ListNode previous = null;
while(current!=null)
{
head = current.next;
current.next = previous;
previous = current;
current = head;
}
return previous;
}
}
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 current = head;
ListNode previous = null;
while(current!=null)
{
head = current.next;
current.next = previous;
previous = current;
current = head;
}
return previous;
}
}