A method to print linked list in reverse/backward order in python

孤街浪徒 提交于 2019-12-24 16:13:51

问题


I'm writing a class called LList and in the class I defined a couple of methods. I am having issue with writing a method to print the linked list in backward order.

class Node(object):
    def __init__(self, data=None, nextNode=None):
        self.data = data
        self.nextNode = nextNode

class LList(object):

    def __init__(self, head=None):
        self.head = head
        self.size = 0

    def insert(self, node):

        if not self.head:
            self.head = node
            self.size += 1
        else:
            # set new nodes pointer to old head
            node.nextNode = self.head
            # reset head to new node
            self.head = node
            self.size +=1

    def getSize(self):
        return self.size

    def printLL(self):
        mynode = self.head
        c = 0
        while mynode:
            c += 1
            print(mynode.data, c)
            mynode = mynode.nextNode

#a method for class that prints list backwards.       
    def reverse(self):


#main program

    MyList = LList()
    MyList.insert(Node("NJ"))
    MyList.insert(Node("NR"))
    MyList.insert(Node("OH"))

    # Use my print method
    MyList.printLL()
    #print in reverse
    MyList.reverse()

回答1:


class Node(object):

          def __init__(self, data=None, next_node=None):
              self.data = data
              self.next = next_node

       def ReversePrint(head):
           if head == None:
              return
           else:
             ReversePrint(head.next)
             print(head.data)

Let's take an example Linked List: 1->2->3 Walking through the code, the function ReversePrint is given a link to the head of our Linked List, which is 1. We see that head is not equal to null so we move to the second line of the code, which is the first recursive call to head.next, which is 2. Again we see that this new "head" is not equal to null, so we do a second recursive call, this time passing the node that contains 3. We see that this new "head" is not equal to null, so we do a third recursive call on head.next, which is null in this case. So we return, since we hit our base case. We are now back in our second recursive call, and we move to the line of code that comes after the recursive call, which is the print statement. We print 3. Since this recursive call is now complete, we move back to the first recursive call, and print 2. Finally, we are back in our initial function call, and we print 1. Therefore, successfully printing our Linked List in reverse order.




回答2:


Well, unless you have a double-linked list, your best option is to traverse the whole linked list saving everything in memory and then print it.

This could be a draft of your code:

def print_reversed(self):

    node = self.head
    values = []
    while node:
        values.append(node.data)
        node = node.nextNode

    for value in reversed(values):
        print(value)

This somehow defeates the purpose of a linked list. You could do it recursively as well, but that would look messy IMO.




回答3:


I expect that your issue is due to the fact that there is no efficient way to iterate backwards over a singly-linked list.

I've enhanced your code slightly by the use of some magic methods (aka dunder methods): methods whose names (usually) begin and end with double underscores. You can read about them in the docs under Special method names.

An object's __str__ method gets called when the object is passed to the str built-in function (which happens implicitly when you attempt to print the object). If an object doesn't have a __str__ method its __repr__ method is called; it's generally a good idea to define at least one of those two methods, otherwise when you try to print your object the default __repr__ method inherited from the generic object will be called.

I've changed your getSize method to __len__, which gets called when an object is passed to the len built-in function.

An object's __iter__ method gets called when it's passed to the iter built-in function, either explicitly or when you attempt to iterate over the object in some kind of for loop, or when you pass it to list or similar constructors. It generally works in conjunction with the __next__ method, which is (unfortunately) named next in Python 2. When an object has these methods it's relatively easy to iterate over it in various ways.

To do the reverse printing we can simply pass the instance to list, and pass the resulting list to reversed, which returns an iterator that iterates backwards over its list argument.

The code below is written for Python 2; change the next method to __next__ for Python 3.

class Node(object):
    def __init__(self, data=None, nextNode=None):
        self.data = data
        self.nextNode = nextNode

    def __str__(self):
        return str(self.data)

class LList(object):
    def __init__(self):
        self.head = None
        self.current = None
        self.size = 0

    def insert(self, node):
        if self.head is not None:
            # set new node's pointer to old head
            node.nextNode = self.head
        self.head = node
        self.size += 1

    def __len__(self):
        return self.size

    def __iter__(self):
        self.current = self.head
        return self

    def next(self):
        current = self.current
        if current is None:
            raise StopIteration
        else:
            self.current = current.nextNode
            return current

    def printLL(self):
        for i, node in enumerate(self, 1):
            print(node, i)

    # print the list backwards
    def reverse_print(self):
        c = len(self)
        for node in reversed(list(self)):
            print(node, c)
            c -= 1


# main program
mylist = LList()
mylist.insert(Node("NJ"))
mylist.insert(Node("NR"))
mylist.insert(Node("OH"))

print(len(mylist))

# print forwards
mylist.printLL()

#print the nodes using a list comprehension
print([str(node) for node in mylist])

#print in reverse
mylist.reverse_print()

output

3
OH 1
NR 2
NJ 3
['OH', 'NR', 'NJ']
NJ 3
NR 2
OH 1


来源:https://stackoverflow.com/questions/34265140/a-method-to-print-linked-list-in-reverse-backward-order-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!