Python中的单链接列表添加,删除,插入

时间:2016-07-26 14:10:26

标签: python data-structures linked-list

我正在尝试使用添加,删除和插入方法来实现单链表。我对插入方法感到困惑。

GC.KeepAlive

链接列表:

class Node(object):

def __init__(self, data, next):
    self.data = data
    self.next = next

class SingleList(object):

head = None
tail = None

def printList(self):
    print "Link List:"
    current_node = self.head
    while current_node is not None:
        print current_node.data, " --> ",
        current_node = current_node.next
    print None

def add(self, data):
    node = Node(data, None)
    if self.head is None:
        self.head = self.tail = node
    else:
        self.tail.next = node
    self.tail = node

def insert(self, before, nextdata):
    #nextdata is to be inserted before 'before'
    #before is actually a data 
    #but it has dif name in this def to avoid confusion with 'data'
    current_node = self.head
    previous_node = None
    while current_node is not None:
        if current_node.data == before:
            if previous_node is not None:
                current_node.next = current_node
        previous_node = current_node
        current_node = current_node.next

def remove(self, node_value):
    current_node = self.head
    previous_node = None
    while current_node is not None:
        if current_node.data == node_value:
            # if this is the first node (head)
            if previous_node is not None:
                previous_node.next = current_node.next
            else:
                self.head = current_node.next
        # needed for the next iteration
        previous_node = current_node
        current_node = current_node.next

链接列表:

1  -->  2  -->  3  -->  4  -->  5  -->  None

例如,如果我正在尝试插入(4,9),在4之前插入数字9。

3  -->  4  -->  6  -->  10  -->  None

任何帮助都会做,片段,建议任何不是勺子喂养。谢谢!

1 个答案:

答案 0 :(得分:0)

您必须将插入内容重写为:

def insert(self, before, nextdata):
    #nextdata is to be inserted before 'before'
    #before is actually a data
    #but it has dif name in this def to avoid confusion with 'data'
    current_node = self.head
    previous_node = None
    while current_node is not None:
        if current_node.data == before:
            if previous_node is not None:
                temp_node = current_node
                current_node = Node(nextdata, temp_node)
                previous_node.next = current_node
            else:
                new_node = Node(nextdata, current_node)
                self.head = new_node
            break
        previous_node = current_node
        current_node = current_node.next

这将照顾它。当您插入新节点时,您必须打破循环,否则它将是无限的。