Home > OS >  Python - linked list
Python - linked list

Time:09-11

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()

CodePudding user response:

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
  • Related