Leetcode Tag Search | Back

Linked List

Category: /template

Reverse Linked list

Explaination Details Template Index

Iteration version

def reverse(head):
    """ pre/cur/next, simplest solution """
    pre = None, cur = head
    while cur:
        next = cur.next
        cur.next = pre
        pre = cur
        cur = next
    return pre

def reverse(head):
    """ using dummy head is a trick to many linked list problems """
    if not head: return None
    dummy = ListNode()
    dummy.next = head
    while head.next:
        next = head.next
        head.next = next.next
        next.next = dummy.next
        dummy.next = next
    return dummy.next

iteration version

Recursion version

def reverse(ListNode head):
    if not head: return None
    if not head.next: return head
    last = reverse(head.next)
    head.next.next = head
    head.next = null
    return last

recursion version

Reverse first N node

successor = None
def reverseN(head, n):
    if n == 1:
        successor = head.next
        return head
    last = reverseN(head.next, n-1)
    head.next.next = head
    head.next = successor
    return last

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)