如何为双向链接列表创建一个insertAfter函数C ++

时间:2019-02-10 03:34:38

标签: c++ nodes doubly-linked-list

我试图创建一个insertAfter函数,在该函数中它通过引用接受一个值,然后将该值插入当前节点之后。我不确定如何实现代码。

下面是头文件以及我尝试过的内容,但无法编译。

#include <iostream>
#include <string>

class DoublyLinkedList {
public:
    DoublyLinkedList();
    ~DoublyLinkedList();
    void append (const string& s);
    void insertBefore (const string& s);
    void insertAfter (const string& s);
    void remove (const string& s);
    bool empty();
    void begin();
    void end();
    bool next();
    bool prev();
    bool find(const string& s);
    const std::string& getData() const;
private:
    class Node
    {
    public:
        Node();
        Node(const string& data);
        ~Node();
        Node* next;
        Node* prev;
        string* data;
    };
    Node* head;
    Node* tail;
    Node* current;
};

void DoublyLinkedList::insertAfter(const string& s)
{
    // Node *temp, *var;
    //var=(Node *)malloc(sizeof(Node));
    if(head == NULL)
    {
        append(s);
    }
    temp->data=current;
}

void DoublyLinkedList::append(const string& s)
{
    //create a new Node
    current = new Node(s);
    if (this->empty())//check if it is empty or not
    {
        this->head = this->tail = current;
    }else{
        //append to tail
        current->prev = tail;
        tail->next = current;
        tail = current;
    }
}

#endif

1 个答案:

答案 0 :(得分:-1)

-创建一个新节点并存储传入的数据。将当前指针设置为head。

Node * newNode = new Node(s);
current=head;

-您必须使用一个循环遍历LinkedList,该循环使用2个指针检查每个节点的值,该指针落后于检查节点值的那个指针。

while(current->data != insertAfter- 
>data)
{
current=current->next;}

-一旦找到合适的电流节点,循环就应该停止。将新节点的下一个指针设置为insertAfter的下一个指针,并将上一个指针设置为insertAfter节点。

newNode->next = insertAfterNode->next;
newNode->prev = insertAfterNode;

-然后将当前的下一个指针设置为要插入的节点。

current->next = newNode;

此外,请确保添加每个可能的案例。如果是在其后插入了尾部,请确保将尾部指针设置为newNode,并且如果将其插入头部,则将其设置为相同。遍历循环后,放入:

if(tail->data==current->data)
{
    tail = newNode;
}

if(head->data==current->data)
{
    head=newNode;
}

编辑:由于这是一个双重的LinkedList,因此可以实现prev指针来代替TrailCurrent,这完全不需要。