Reversing a linked list in python

前端 未结 11 2352
失恋的感觉
失恋的感觉 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:08

    I tried a different approach, in place reversal of the LList. Given a list 1,2,3,4

    If you successively swap nearby nodes,you'll get the solution.

    len=3 (size-1)
    2,1,3,4
    2,3,1,4
    2,3,4,1
    
    len=2 (size-2)
    3,2,4,1
    3,4,2,1
    
    len=1 (size-3)
    4,3,2,1
    

    The code below does just that. Outer for loop successively reduces the len of list to swap between. While loop swaps the data elements of the Nodes.

    def Reverse(head):
        temp = head
        llSize = 0
        while temp is not None:
            llSize += 1
            temp = temp.next
    
    
        for i in xrange(llSize-1,0,-1):
            xcount = 0
            temp = head
            while (xcount != i):
                temp.data, temp.next.data = temp.next.data, temp.data
                temp = temp.next
                xcount += 1
        return head
    

    This might not be as efficient as other solutions, but helps to see the problem in a different light. Hope you find this useful.

提交回复
热议问题