LeetCode 206 (Reverse Linked List)
思路:
如果原链表为空或只有一个结点,则直接返回原链表(后面会发现只有一个结点的情况可以合并到下面的情况)。
遇到其他情况则可以创建一个新链表。以原链表的头为新链表的尾,在遍历原链表时把遍历到的链表逐个插入到新链表的前面。
在链表前插入结点的步骤如下:
- 创建一个新的结点frontNode.
- 令frontNode的后继为链表头部。
- 令更新后的链表的头部为frontNode.
代码:
# 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 == None:
return head
newNode = ListNode(head.val)
head = head.next
while head != None:
frontNode = ListNode(head.val)
frontNode.next = newNode
newNode = frontNode
head = head.next
return newNode
另外,可以用递归的方式,不创建新链表地反转链表。
思路:
设链表Ln有n个结点,头为head.
如果我们已经得到以head的后继为头的链表L(n-1)的反转链表L’(n-1),那么我们只需要让L’(n-1)的尾部的后继为head即可得到Ln的反转链表L’n. 当然,不要忘记把head的后继修改为空,以让它成为新链表的尾部。
这里的递归终止条件为head为空或head的后继为空(因为递归过程中需要修改head的后继的后继,即反转的子链表的尾部,所以head的后继为空这个条件也要作为递归终止条件)。
代码:
# 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 == None or head.next == None:
return head
newHead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newHead