Love Bisaria
Love Bisaria

Reputation: 167

LinkedList code in python

__author__ = 'jarvis'
class Node:
    def __init__(self, num):
        self.next = None
        self.data = num

class LList:
    def __init__(self, h=None):
        self.head = None

    def insert_node(self, num):
        node = Node(num)
        if self.head is None:
            self.head = node
        else:
            node.next = self.head
            self.head = node

    def print_list(self):
        node = self.head
        while not (node is None):
            print node.data
            node = node.next

lis = LList()
lis.insert_node(10)
lis.insert_node(20)
lis.insert_node(30)
lis.print_list()

I am very new to Python. I am trying to create a LinkedList. No error is shown but nothing is getting displayed. When I am trying to debug. The program is exiting without anything happening. Not able to understand what the problem is.

Upvotes: 1

Views: 238

Answers (1)

Upio
Upio

Reputation: 1374

You shouldn't be setting node.next = self.head. You should be maintaining a pointer to both the head and tail. I've modified your code below.

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

class LList:
    def __init__(self, h=None):
        self.head = None
        self.tail = None

    def insert_node(self, num):
        node = Node(num)
        if self.head is None:
            self.head = node
            self.tail = self.head
        else:
            self.tail.next= node
            self.tail = node

    def print_list(self):
        node = self.head
        while not (node is None):
            print node.data
            node = node.next

Upvotes: 1

Related Questions