LeetCode 206 [Reverse Linked List]

原题

翻转一个链表

样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

解题思路

  • 基础链表问题,同向双指针
  • temp = head.next //让temp记住head.next指向的节点
  • head.next = prev //剪短head与原来head.next之间的关系,将head.next指向prev
  • prev指向head,即向前移动一步
  • head指向temp,也是向前移动一步
  • 方法二 Recursion

完整代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# 方法一 :Non-recursion
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None
        while head:
            temp = head.next
            head.next = prev
            prev = head
            head = temp
        return prev

# 方法二 :Recursion
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return head
        next = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return next

你可能感兴趣的:(LeetCode 206 [Reverse Linked List])