Jerry Hu February 2016

Python Doubly Linked List - Inserts data into a new node after the given node

I am writing the code for doubly linked list in python. However, I am struggling how to insert data into a new node after the given node. And my understanding is really wrong for constructing a doubly linked list's insertAfter() method in python. I want to know how to fix the code.

This is my code so far:

class Node:   
   # Constructor to initialize data
   # If data is not given by user,its taken as None 
    def __init__(self, data=None, next=None, prev=None):
        self.data = data
        self.next = next
        self.prev = prev

class Doubly_Linked_List:
    def __init__(self):
        self.head = None
        self.tail = None

    #  Inserts data into a new node after the given node
    def insertAfter(self, node, data):
        runner = Node(None, data, node, None)
        runner.next = self.head
        if self.head is not None:
            self.head.prev = runner
        self.head = runner

    # # Adds the given value as the last value in the list
    def addLast(self, data):
        if self.head is not None:
            runner = self.head
            while(runner.next != None):
                runner = runner.next
            runner.next = Node(data, None, runner)
            self.tail = runner.next
        else:
            self.head = Node(data)
            self.tail = self.head

    def Print_Next_List(self): # Traverse forwards
        runner = self.head
        while (runner is not None):
            print(runner.data) 
            runner = runner.next

    def Print_Prev_List(self): # Traverse Backwards
        runner = self.tail
        while (runner is not None):
            print(runner.data)
            runner = runner.prev

# Initializing list
aList = Doubly_Linked_List()

aList.addLast(3)
aList.addLast(5)
aList.addLast(7)
aList.addLast(9)
aList.addLast(11)

aList.Print_Next_List()
print()
aList.Print_Prev_List()

aList.insertAfter(5,7) #This shows me an error.

Answers


Fredrik February 2016

I have no idea what you are doing in:

def insertAfter(self, node, data):
    runner = Node(None, data, node, None)
    runner.next = self.head
    if self.head is not None:
        self.head.prev = runner
    self.head = runner

This should be:

def insertAfter(self, node, data):
    newNode = Node(data, node.next, node)
    node.next = newNode

Here you create a new Node with the data passed and place it after the passed Node.

Post Status

Asked in February 2016
Viewed 1,641 times
Voted 7
Answered 1 times

Search




Leave an answer