首页 > 解决方案 > Insert new element as the head of the Linkedlist Python

问题描述

I want to add an element at the beginning of a Linkedlist, but None is added instead of the actual element

class Node:
    #initialize the head node to none if not provided and set the next node to none
    def __init__(self,data=None):
        self.data = data
        self.next = None

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


    def append(self,data):
        #creating the node with the data parameter
        new_node = Node(data)
        current_node = self.head
        while current_node.next is not None:
            current_node = current_node.next
        #when we have reached the end of list
        current_node.next = new_node


    def display(self):
        #container for the nodes
        node_elements = []
        current_node = self.head

        while current_node.next is not None:
            current_node = current_node.next
            node_elements.append(current_node.data)
        print(node_elements)

    #Here is where there is the issue
    def insert_as_first_element(self,data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

标签: pythonpython-3.xpython-2.7

解决方案


Your insert method seems fine. The problems seems to be that you initialize self.head as an empty Node() but never update that node's data. Adding a repr method to Node as

def __repr__(self):
    return "(%r, %r)" % (self.data, self.next)

we see that after appending or inserting the numbers from range(10), the result looks like this:

(None, (0, (1, (2, (3, (4, (5, (6, (7, (8, (9, None)))))))))))
(9, (8, (7, (6, (5, (4, (3, (2, (1, (0, (None, None)))))))))))

Instead, you should initialize self.head as None and add an accordant check to append:

def __init__(self):
    self.head = None

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

Then, the result looks like this:

(0, (1, (2, (3, (4, (5, (6, (7, (8, (9, None))))))))))
(9, (8, (7, (6, (5, (4, (3, (2, (1, (0, None))))))))))

You also have to adapt your display method as it skips the first element in the list, which is probably why you did not notice the bug for append.

def display(self):
    node_elements = []
    cur = self.head
    while cur is not None:
        node_elements.append(cur.data)
        cur = cur.next
    print(node_elements)

推荐阅读