-1

can anybody explain why it is showing me and how to print it? what am I doing wrong and how to print this object reference?

i have also tried printing new_list(inside sort() ) but still the same I am printing list then why it is not showing

I know some of the people asked before about related to this...but still I didn't get it.

class node(object):
    def __init__(self, d, n=None):
        self.data=d
        self.next_node=n

    def get_data(self):
        return self.data

    def set_data(self,d):
        self.data=d

    def get_next(self):
        return self.next_node

    def set_next(self, n):
        self.next_node=n




    def has_next(self):
        if self.get_next() is not None:
            return True
        else:
            False







class LinkedList(object):
    def __init__(self, r=None):
        self.root=r
        self.size=0

    def get_size(self):
        return self.size

    def add(self,d):
        new_node = node(d, self.root)
        self.root = new_node
        self.size+=1


    def sort(self):
        if self.size>2:
            newlist = []
            this_node = self.root
            newlist.append(this_node)
            while this_node.has_next():
                this_node = this_node.get_next()
                newlist.append(this_node)
            newlist = sorted(newlist ,key = lambda node: node.data,reverse=True)

            newLinkedList = LinkedList()
            for element in newlist:
                newLinkedList.add(element)
            return newLinkedList
        return self





new_list=LinkedList()
new_list.add(10)
new_list.add(20)
new_list.add(30)


new_list.sort()

i expected that it will print list print a list

but it is showing <main.LinkedList object at 0x00E20BB0> how to print this object ?

  • Simply implement `__repr__` and potentially `__str__` in your classes. What they do and the difference between them is explained [here](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr) – shmee Aug 09 '19 at 04:45

1 Answers1

0

You are not printing out node values of the linked list instead you are printing out the return value of the sort() function which is an object of the class LinkedList.

If you want to print the linked list, you have to traverse the list and print out each node value individually.

Here is the recursive solution of how you can print a linked list.

def print_list(head):
    if head != null:
        print(head.val)
        print_list(head.next)

You can call this method after calling the sort function

Ezio
  • 2,837
  • 2
  • 29
  • 45