简体   繁体   English

在双链表中的某个节点之前插入节点

[英]Inserting nodes before a certain node in Doubly Linked List

I have created Doubly Linked List as below 我创建了如下的双向链接列表

8 <-> 2 <-> 12

I have to insert following nodes before node "2" 我必须在节点“ 2”之前插入以下节点

Nodes to insert -(8,22,23,15) 要插入的节点-(8,22,23,15)

Node "8" is already present before node "2", In this case i don't want to insert node "8" again. 节点“ 2”之前已经存在节点“ 8”,在这种情况下,我不想再次插入节点“ 8”。 Is there any way to check "node to insert" is already present before the node or not? 有什么方法可以检查节点之前是否存在“要插入的节点”?

I want final DLL as 8 <-> 22 <-> 23 <-> 15 <-> 2 <-> 12 我想要最终的DLL为8 <-> 22 <-> 23 <-> 15 <-> 2 <-> 12

However, if you don't want to repeat series: 但是,如果您不想重复序列:

Current List: 当前列表:

1 ↔ 2 ↔ 3 1 2 3

Insert before 3: (1, 2, 4) 在3: (1、2、4) 之前插入

Result wanted: 想要的结果:

1 ↔ 2 ↔ 4 ↔ 3 1↔2↔4↔3

It gets a little bit more complicated, but not much. 它变得有点复杂,但不多。

First , check if the node before the one you use as base matches any of your to introduce nodes. 首先 ,检查用作基础节点之前的节点是否与您要引入的节点中的任何一个匹配。 Starting for the last one (so you get always the longest series repeated, and avoid it). 从最后一个开始(这样一来,您总是会得到最长的序列,并避免这样做)。

If one matches check if the rest of the serie before it matches too. 如果匹配,则检查之前的其余系列是否也匹配。 If it does, start from the next (or add none, if it's the last); 如果是这样,则从下一个开始(如果是最后一个,则不添加); if it doesn't, go back to First step. 如果没有,回到第一步

Second and last After you have selected the next node to add (if you didn't match any on First , just start on the first one) just add them before the base . 第二个和最后一个选择了要添加的下一个节点(如果在First上没有匹配的节点,则从第一个节点开始),然后在base之前添加它们。

This is pseudocode, since I don't know your exact implementation: 这是伪代码,因为我不知道您的确切实现:

Considering: 考虑:

int[] toAdd = {1, 2, 4};

For example, you can use recursivity: 例如,您可以使用递归:

main {
    int from = 0;
    for (int i = toAdd.length - 1; i >= 0; i--) {
        if (checkSerie(toAdd, i, base) {
            from = i;
            break;
        }
    }

    // And add:
    for (int i = from; i < toAdd.length; i++) {
        addBefore(3, toAdd[i]); // Your add method.
    }
}

private boolean checkSerie (int[] toAdd, int index, Node base){
    Node prev = base.prev;
    if (index < 0) {
        return true;
    }

    if (toAdd[index] != prev) {
        return false;
    }

    return checkSeriei (toAdd, index - 1, prev);
}

Note: I haven't tested this, it might be buggy (maybe some wrong -1 or stuff like that), but should be enough to help you get the idea. 注意:我还没有测试过,它可能有问题(可能是错误的-1或类似的东西),但应该足以帮助您理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM