【问题标题】:Inserting in the middle of a doubly linked list- Python在双向链表中间插入 - Python
【发布时间】:2012-11-12 22:56:42
【问题描述】:

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

【问题讨论】:

  • 我们需要查看您当前的代码来帮助您。否则,我们只是在实现我们自己的双向链表,而不是帮助您修复您的双向链表。您能否提供您的代码或它的 sn-p,以便我们有一个起点来帮助您?
  • 此外,我们还需要了解更多“我遇到麻烦”的信息——尽可能具体,以获得最佳帮助。

标签: python list linked-list


【解决方案1】:

我也是,我是 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 2013-09-01
    • 2011-07-20
    相关资源
    最近更新 更多