不典型地插入双连接列表

Not typical inserting into doubly-linked list

本文关键字:连接 列表 插入 不典型      更新时间:2023-10-16

我有一个任务我不知道如何'bite'。

编写一种方法,该方法将一对节点插入双链接列表中 使用键的键,每个节点都用给定的键

键 在

函数返回插入的对数。

我应该如何解释?如何实施它?

模板< ...

int insert (double where, double before, double after);

似乎很合理。对于每个匹配where的密钥,您必须在它之前插入before,然后在其之后插入after

所以,假设您有:

||- 1 <-> 2 <-> 3 <-> 2 <-> 2 -||

然后呼叫:

quant = insert (2, 3.14, 2.72);

最终将修改列表如下:

||- 1 <-> 3.14 <-> 2 <-> 2.72 <-> 3 <-> 3.14 -+
                                              |
+---------------------------------------------+
|                              
+-> 2 <> 2.72 <> 3.14 <> 2 <> 2.72 -||

并返回值3

除了在节点之前和之后插入的行为外,这与任何其他插入操作完全一样,事实是A doubly 链接列表实际上使事情变得更容易。这种野兽的伪代码是:

# HEAD is pointer to first element, TAIL to last.
# Process entire list, doing the insertions as needed.
def insert(where, before, after):
    count = 0
    curr = HEAD
    while curr != null:
        if curr.data == where:
            count = count + 1
            insertBefore(curr, before)
            insertAfter(curr, after)
            curr = curr.next # see note (a) below.
        curr = curr.next
   return count
# Insert before a node, special processing needed for head.
def insertBefore(curr, value):
    node = new element
    node.data = value
    node.next = curr
    if curr == HEAD:
        HEAD = node
    else:
        curr.prev.next = node
def insertAfter(curr, value):
    node = new element
    node.data = value
    node.next = curr.next
    curr.next = node
    if curr == TAIL:
        TAIL = node

(a) May 想知道为什么在发生插入的情况下,我两次将指针推进两次。如果您考虑whereafter都具有相同的值(例如7)。

没有额外的进步,您会在列表中找到7,然后在其后立即插入另一个7。然后,您会发现 7,然后在其后立即插入另一个7。这会持续一段时间。如果您愿意,请继续尝试,完成后回来。

...

好吧,希望不会太很久就意识到没有某种干预就不会停止,例如 ctrl-c 无限记忆: - )

进步可确保您实际上不会处理在列表中添加的节点,只有在该过程启动时已经在其中的节点。