Click here to Skip to main content
15,912,504 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
reversing a linkedlist using 3 pointer?
cant understand what is the problem?
pls suggest any other iterative solution too.. 
reversing a linkedlist using 3 pointer?
cant understand what is the problem?
pls suggest any other iterative solution too..

outcome should be 87654321(reverse of a linkedlist)
but currently the output is 1
i think there is problem in reverse function pointers
    
#reversing a linkedlist
    class Node:
        def __init__(self,data):
            self.data=data
            self.next=None
    class LinkedList:
        def __init__(self):
            self.head=None
        def push(self,data):
            new_node=Node(data)
            new_node.next=self.head
            self.head=new_node
        def printlist(self):
            temp=self.head
            print()
            while temp:
                print(temp.data,end=' ')
                temp=temp.next
        def append(self, new_data): 
            new_node = Node(new_data) 
            if self.head is None: 
                self.head = new_node 
                return
            last = self.head 
            while (last.next): 
                last = last.next
            last.next =  new_node
        def reverse(self):
            prev=None
            current=self.head
            nnext=current.next
            while nnext:
                current.next=prev
                prev = current
                current = nnext
                nnext=nnext.next
            current.next=prev
    if __name__=='__main__':
        llist=LinkedList()
        llist.append(1)
        llist.append(2)
        llist.append(3)
        llist.append(4)
        llist.append(5) 
        llist.append(6)
        llist.append(7)
        llist.append(8)
        llist.printlist()
        llist.reverse()
        llist.printlist()


What I have tried:

there is some problem with the pointers of my reverse function
Posted
Updated 8-Oct-19 1:30am

1 solution

It's pretty obvious, when you think about it - but if you can't work it out, then use the debugger to follow through what exactly your code is doing. If you don;t know how to use it, then it would be a really good idea to learn - it's a lot easier to do that on a tiny bit of code like this than it would be on a 100,000 later project!
This will help you learn how: python debugger - Google Search[^]


Hint: keep an eye on what happens to the head of the list.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900