0

I am trying to insert an item after another one but my code doesn't work. The below function insert_after_another doesn't work.

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

    def insert_end(self,data):
        x = Node(data)
        if self.head == None:
            self.head = x
            return
        temp = self.head
        while(temp.next != None):
            temp = temp.next
        temp.next = x

   def insert_after_another(self,old_data,new_data):
        t_old = Node(old_data)
        d_new = Node(new_data)
        temp = self.head
        while(temp):
            if temp.data == old_data:
                d_new.next = t_old.next
                t_old.next = d_new

            temp = temp.next

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


if __name__=='__main__':
    llist = LinkedList()
    llist.insert_end(3)
    llist.insert_end(32)
    llist.insert_after_another(3,13)

I am not getting any result when I try to print the data.

2 Answers 2

1
d_new.next = t_old.next

in this line t_old.next pointing to nothing nor there is a pointer to it, it is just a node you created before.

def insert_after_another(self,old_data,new_data):
        d_new=Node(new_data)
        temp=self.head
        while(temp):
            if temp.data==old_data:
                d_new.next = temp.next
                temp.next = d_new
                break

This may work I think. You just need two swaps only, The new node should point the old node's next and the old node should point to the new one.

Sign up to request clarification or add additional context in comments.

Comments

0

This will be able to resolve your problem. Consider having correct identations and renaming your method.

def insert_after_value(self, old_data, new_data):

    if self.head is None:
        return

    if self.head.data == old_data:
        self.head.next = Node(new_data, self.head.next)
        return

    temp = self.head

    while temp:
        if temp.data == old_data:
            temp.next = Node(new_data, temp.next)
            break

    temp = temp.next

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.