简体   繁体   中英

Insert after another item in linked list in python

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM