Leetcode 206.反转链表

206.反转链表

题目

反转一个单链表。

1
2
3
4
示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

方法

方法1:迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
last = None
while head:
tmp = head.next
head.next = last
last = head
head = tmp
return last

方法2:递归

假设链表$n_1 \to n_2 \to n_{k-} \to n_k \to n_{k+1} \to …\to n_m \to None$中,结点$n_{k+1}$到$n_m$已经反转了,当前结点就是$n_k$

现在只需要将$n_{k+1}$的下个结点设为$n_k$即可:$n_k.next.next=n_k$
当然,还需要将$n_1.next=None$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return
if not head.next:
return head
node = self.reverseList(head.next)
head.next.next = head
head.next = None
return node