简体   繁体   中英

How to format the output print statement to print linked list?

So I trying to print the linked list after the string but I not able to do it. The print statement is in pop function inside unordered class

The linked list always get printed first and then the string ie

54 26 56 93 17 77 31 7
Original Linked List: None

My Desired Output

Original Linked List: 54 26 56 93 17 77 31 7

class Node:
    def __init__(self, initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

class UnorderedList:

    def __init__(self):
        self.head = None

    def isEmpty(self):
        return self.head == None

    def printList(self):
        temp = self.head
        while (temp):
            print(temp.data, end=" ")
            temp = temp.next
        print('\n')

    def pop(self):
        print('Original Linked List:' self.printList())
        current = self.head
        previous = None
        while current.getNext() != None:
            previous = current
            current = current.getNext()
        previous.setNext(current.getNext())
        print('New linked list after pop is:', self.printList())

So I have tried formatting it with

print(f'Orginal Linked List: {self.printList()})
print('Original Linked List: %d' %(self.printList()))

Nothing really works I am new to programming I appreciate your help.

You need a function that returns a list rather than printing a list. It's easiest if you name this function __str__ because then it'll get called automatically whenever anything tries to convert your list to a string.

Change:

    def printList(self):
        temp = self.head
        while (temp):
            print(temp.data, end=" ")
            temp = temp.next
        print('\n')

to:

    def __str__(self):
        s = ''
        temp = self.head
        while temp:
            s += str(temp.data) + " "
            temp = temp.next
        return s[:-1]

and then you can do:

print(f'Original Linked List: {self})

which will automatically call your __str__ method and put the result into the f-string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM