How can I write a recursive function to reverse a linked list?

前端 未结 8 837
我寻月下人不归
我寻月下人不归 2021-02-09 12:39

I am looking to do it with Python. And I don\'t want to just print it in reverse, but actually reverse the given nodes. I have seen it done in other languages but had trouble fi

8条回答
  •  孤独总比滥情好
    2021-02-09 13:08

    I have created a simple implementation of linked list with a reverse method that uses recursion.

    class Node(object):
        def __init__(self,initdata):
            self.data = initdata
            self.next = None
    
    class LinkedList(object):
        def __init__(self):
            self.head = None
    
        def isEmpty(self):
            return self.head == None
    
        def add(self,data): #this method adds node at head
            temp = Node(data)
            temp.setNext(self.head)
            self.head = temp
    
        def traverse(self):
            current = self.head
            while current:
                if current.getNext():
                    print(current.data,end="->")
                else:
                    print(current.data)
                current = current.getNext()
    
        def reverse(self,item):
            if item.next == None:
                self.head = item
                return
            self.reverse(item.next)
            temp = item.next
            temp.next = item
            item.next = None
    
    
    def main():
        mylist = LinkedList()
        mylist.add(15)
        mylist.add(20)
        mylist.add(25)
        mylist.add(30)
        mylist.traverse()
        mylist.reverse(mylist.head)
        mylist.traverse()
        print(mylist.head.data)
    
    if __name__ == "__main__":
        main()
    

    Output:

    Before:
    30->25->20->15
    After:
    15->20->25->30
    

提交回复
热议问题