Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – linked list

Why is it only printing 6 and 7? I need to print all the values.
I believe there is some issue with get() as self.head is being updated somewhere?
If so, how can I declare self.head here as the beginning so that it prints all the elements.
Thanks in advance.

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

class list:
    def __init__(self):
        self.head = None

    def prepend(self,data):
        n = Node(data)
        if self.head is None:
            self.head = n
        else:
            n.next = self.head
            self.head = n

    def append(self,data):
        n = Node(data)
        if self.head is None:
            self.head = n
        else:
            while self.head.next:
                self.head = self.head.next
            self.head.next = n

    def get(self):
        while self.head:
            print(self.head.data)
            self.head = self.head.next

la = list()
la.prepend(1)
la.append(4)
la.append(5)
la.append(6)
la.append(7)
la.get()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should only update the head when you insert at the begining. You were modifying the head when you were appending to the end and printing the linked list.

Here is my modified code:

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


class LinkedList:
    def __init__(self):
        self.head = None

    def prepend(self,data):
        n = Node(data)
        if self.head is None:
            self.head = n
        else:
            n.next = self.head
            self.head = n

    def append(self,data):
        n = Node(data)
        if self.head is None:
            self.head = n
        else:
            last_node = self.head
            while last_node.next:
                last_node = last_node.next
            last_node.next = n

    def get(self):
        if self.head:
            node_to_print = self.head
            while node_to_print.next:
                print(node_to_print.data)
                node_to_print = node_to_print.next
            print(node_to_print.data)

Prints:

1
4
5
6
7
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading