1

The "append" method is not working correctly. It's only going inside the 'if" statement of the "append' method and not entering into the while loop.

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

class Linkedlist:
    def __init__(self):
        self.head=Node()

    def append(self,data):
        new_node=Node(data)
        if self.head.data is None:
            self.head=new_node          
        cur_node=self.head
        while cur_node.next is not None:
            cur_node=cur_node.next
        cur_node=new_node

    def insert_after_node(self,prev_node,data):
        new_node=Node(data)
        if prev_node is None:
            print("node that you have entered does not exist")
        new_node.next=prev_node.next
        prev_node.next=new_node

    def display(self):
        current=self.head
        while current.next is not None:
            print(current.data)
            current=current.next

List=Linkedlist()
List.append("A")
List.append("B")
List.append("C")
List.insert_after_node(List.head,"g")
List.display()

Expected output: AgBC
Actual Output: A

3
  • 1
    Your append method sets cur_node to a bunch of stuff, but ultimately doesn't do anything with it. Did you mean to set cur_node.next to something? Commented Feb 13, 2019 at 16:18
  • Node instance use data as keyword argument not positional, so first of all you should use Node(data=data) instead of Node(data) Commented Feb 13, 2019 at 16:20
  • 1
    @om2c0de: no, that's not needed. You can use positional parameters for keyword arguments just fine. Python assigns positional parameters to each argument in order, and the first argument (past self, provided by the bound method object), is data. Commented Feb 13, 2019 at 16:22

3 Answers 3

1

Your .append() method simply sets a local variable to cur_node to point to new_node. This doesn't change the linked list at all; the last node in the link that was previously assigned to that local variable is not changed.

You instead want to assign to the .next attribute of the last node:

cur_node.next = new_node

The while loop in the method is working fine otherwise.

You also should not use new_node twice, when the list is empty. Exit when you don't yet have a head node with data:

if self.head.data is None:
    self.head=new_node
    return

Personally, I'd set self.head = None instead of self.head = Node(), then use if self.head is None:.

Next, your display function forgets to print the last element. Rather than test for current.next, check if current is None; this is where setting self.head to None for an empty list would work a lot better:

def display(self):
    current = self.head
    while current is not None
        print(current.data)
        current = current.next
Sign up to request clarification or add additional context in comments.

Comments

1

I had the exact same question as you, but my implementation was different and it seems to work just fine.

First I created a node class with all its different methods:

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

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next

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

    def set_next(self, new_next):
        self.next= new_next

The I created my UnorderedList class with its methods too, including append. insert, index and pop I am still working on...

class UnorderedList:
    """
    An unordered list class built from a collection of nodes.
    """
    
    def __init__(self):
        self.head = None

    def is_empty(self):
        return self.head == None
    
    def add(self, item):
        temp = Node(item)
        temp.set_next(self.head)
        self.head = temp

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count += 1
            current = current.get_next()

        return count

    def search(self, item):
        current = self.head
        found = False
        while current != None and not found:
            if current.get_data() == item:
                found = True
            else:
                current = current.get_next()

        return found


    def remove(self, item):
        current = self.head
        previous = None
        found = False
        while not found:
            if current.get_data() == item:
                found = True
            else:
                previous = current
                current = current.get_next()

        if previous == None:
            self.head = current.get_next()
        else:
            previous.set_next(current.get_next())

    def print_list(self):
        current = self.head
        while current != None:
            print(current.data)
            current = current.get_next()

    def append(self, item):
        new_node = Node(item)

        if self.head == None:
            self.head = new_node
            return 
            
        current = self.head
        found_last = False
        while not found_last:
            if current.get_next() == None:
                found_last = True
                current.set_next(new_node)
                
            else:
                current = current.get_next()


    def insert(self, item, pos):
        pass


    def index(self, item):
        pass


    def pop(self):
        pass

I realize my version of append is more verbose, but I was using the traversal method I previously used as part of my size method to make it work, and it seems to work just fine.

I found it easier to create a Node class with its methods separately as it made it easier to visualize how to set the next node and get data from the current one. Hope this helps!

FYI the node class and a lot of the UnorderedList is straight out of Problem Solving with Algorithms and Data Structures in Python by David Ranum and Brad Miller, so I know they work fine!

Comments

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

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

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

    def insert_after_node(self,prev_node,data):
        new_node=Node(data)
        if prev_node is None:
            print("node that you have entered does not exist")
        new_node.next=prev_node.next
        prev_node.next=new_node

    def display(self):
        current=self.head
        while current.next is not None:
            print(current.data)
            current=current.next
        print(current.data)

List=LinkedList()
List.append("A")
List.append("B")
List.append("C")
List.insert_after_node(List.head,"g")

Fixed some bugs for you:

  1. The class name LinkedList mismatch problem

  2. In append, if self.head.data is None, it should set self.head and then return.

  3. In the else part of append, let the last node point to the new node by cur_node.next=new_node

  4. In display, the last node should also be printed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.