Reversing a linked list in python

前端 未结 11 2380
失恋的感觉
失恋的感觉 2020-12-08 12:28

I am asked to reverse a which takes head as parameter where as head is a linked list e.g.: 1 -> 2 -> 3 which was returned from a function already defined I tried to implemen

11条回答
  •  情深已故
    2020-12-08 13:15

    Here is a way to reverse the list 'in place'. This runs in constant time O(n) and uses zero additional space.

    def reverse(head):
      if not head:
        return head
      h = head
      q = None
      p = h.next
      while (p):
        h.next = q
        q = h
        h = p
        p = h.next
      h.next = q
      return h
    

    Here's an animation to show the algorithm running.
    (# symbolizes Null/None for purposes of animation)

提交回复
热议问题