Search code examples
pythonlinked-listdoubly-linked-list

Pointer in doubly linked list pointing at the wrong thing


I'm trying to convert a string into a doubly linked list. I want to be able to traverse it, find a match, and then insert another linked list at a certain position. However, I'm having trouble with my pointers. I have 'current.prev', 'current', and 'current.next' pointers that should all be pointing at the nodes in that order. Instead, my .prev and current pointers always point to the same thing. I need to be able to point at the different parts of the linked list, otherwise I won't be able to traverse back to a certain spot so I can insert a new linked list.

this is the code that creates doubly linked lists for me:

#-----------------------doubly-linked-lists-----------------------#
class NodeD:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None
    

class DoublyLL:
    def __init__(self):
        self.head = None
        
    def append(self, new_data):
        new_node = NodeD(new_data)
        if self.head is None:
            self.head = new_node
            return
        last = self.head
        while last.next:
            last = last.next
        last.next = new_node
        new_node.prev = last
        return
    
    def printList(self, node):
        while node:
            print(node.data, end=""),
            last = node
            node = node.next

this is the code that makes a string into a linked list:

#making-linked-lists-from-strings#

def dnaToLL(dnainput):
    dnaLL = DoublyLL()
    head = NodeD(dnainput[0])
    dnaLL.head = head
    current = dnaLL.head
    for i in range(1, len(dnainput)):
        current.prev = current
        current = current.next
        current.next = NodeD(dnainput[i])
    return dnaLL

I've been using this to test where the pointers are pointing:

dnaLL = dnaToLL(DNA)
dnaLL = dnaLL.head
print(dnaLL.prev.data +dnaLL.data+dnaLL.next.data)

but with this input:

S1 = "neho"
DNA = "imfinehowru"

I get this output:

iim

any idea where I've gone wrong? I am assuming it's where I've tried to make strings into doubly linked lists, but any other order that I put the pointers in gives me errors.

Thank you for your help!


Solution

  • The problem is that whe you do current.prev = current, you're saying "the previous node is the current node" - not the actual previous node.

    Keep in mind that the first node in the list should have .prev = None. You'd only want to set .prev for future nodes. This modification should fix your dnaToLL() function:

    def dnaToLL(dnainput):
        dnaLL = DoublyLL()
        head = NodeD(dnainput[0])
        dnaLL.head = head
        current = dnaLL.head
        for i in range(1, len(dnainput)):
            # note how the order is changed
            current.next = NodeD(dnainput[i])
            current.next.prev = current
            current = current.next
        return dnaLL