0

我是 stackoverflow 和 Python 语言的新手,有一个问题。我知道如何在 Python 中实现单链表,但是在使用双链表时遇到了问题,更具体地说是插入到双链表的中间。谁能帮我写代码来做到这一点?谢谢

4

1 回答 1

5

我也是,我是 Python 新手,但我希望我能帮到你。因此,如果我正确地回答了您的问题,假设您有一些(经典)链表实现,如下所示:

# Simple LinkedList class
class LinkedList:
    def __init__(self, data, prev=None, next=None):
        self.data = data
        self.prev = prev
        self.next = next

    # Just a string representation
    def __str__(self):
        if self.next:
            return '%s %s' % (str(self.data), self.next.__str__())
        else:
            return '%s' % str(self.data)

通过同时从末端迭代到中间,您可以轻松地将元素插入到中间,知道链表的末端。当迭代器相交时,添加元素:

# Insert to middle logic
def insertToMiddle(data, left, right):
    # Iterate
    while True:
        # Test for intersection
        if left.next is right:
            node = LinkedList(data, left, right)
            left.next = node
            right.prev = node
            return
        elif left is right:
            node = LinkedList(data, left.prev, right.next)
            left.next = node
            right.next.prev = node
            return

        # Next iteration
        left = left.next
        right = right.prev

        # This doesn't actually execute for a right call
        if not left or not right:
            return

下面,您可以看到插入前后的链表创建及其表示:

# Sample list creation
node1 = LinkedList(1)
node2 = LinkedList(2,node1)
node3 = LinkedList(3,node2)
node4 = LinkedList(4,node3)
node1.next = node2
node2.next = node3
node3.next = node4

# Test
print node1 
insertToMiddle(5, node1, node4)
print node1
insertToMiddle(6, node1, node4)
print node1
insertToMiddle(7, node1, node4)
print node1

输出:

1 2 3 4                #initial
1 2 5 3 4              #inserted 5
1 2 5 6 3 4            #inserted 6, notice it's right to middle
1 2 5 7 6 3 4          #inserted 7

备注:如果你的列表有奇数个元素(比如 2 3 4),插入到中间是不确定的,所以上面的函数将立即添加到中间的右边(2 3 elem 4)

于 2012-11-12T23:54:16.863 回答