C++ 在双向链表中插入元素逻辑错误

时间:2021-02-19 16:43:45

标签: c++ doubly-linked-list

我正在编写采用未排序元素列表并将它们排序为双向链表的代码。该代码在大多数情况下都有效,元素可以添加到列表的开头和结尾,但是出于某种原因,如果添加的第一个元素将保留在头部(按字母顺序排列的最高位置) head 的地址和 head->next 将是相同的。如果顺序颠倒,尾部也会发生这种情况。这与第 28 行到第 50 行的逻辑有关。

下面的代码是可编译和可运行的。任何有关我哪里出错的帮助将不胜感激。

注意:不得使用 C++ 库或类,这是您自己的练习。

#include <iostream>
#include <cstring>

using namespace std;

struct node
{
    char value[15];
    node *next;
    node *prev;
};

void insert(node *&head, node *&tail, char *value){

    if(!head){
        // empty list create new node
        node* nn = new node;
        
        strcpy(nn->value, value);
        
        nn->next = NULL;
        nn->prev = NULL;
        
        head = nn;
        tail = nn;
    }
    else if(strcmp(value, head->value) < 0){
        // smaller than head.  Update head
        node* nn = new node;
        
        strcpy(nn->value, value);
        
        nn->next = head;
        nn->prev = NULL;
        nn->next->prev = head;
        
        head = nn;
    }
    else if(strcmp(value, tail->value) > 0){
        // larger than tail.  Update tail
        node* nn = new node;
        
        strcpy(nn->value, value);
        
        nn->next = NULL;
        nn->prev = tail;
        nn->prev->next = tail;
        
        tail = nn;
    }
    else{ 
        /* TODO: insert in the middle of the list */ 
    }
}

void printlinkedList(node *ll){
    node *curr = ll;

    while(curr){
        cout << "Value: " << curr->value << "\t";
        cout << "curr: " << curr << "\t";
        cout << "curr->prev " << curr->prev << "\n";
        curr = curr->prev;
    }
}

int main(){

    // Test code
    node *head = NULL;
    node *tail = NULL;

    insert(head, tail, (char*)"aa");
    insert(head, tail, (char*)"bb");
    insert(head, tail, (char*)"cc");
    insert(head, tail, (char*)"dd");

    cout << "\nhead:\t\t" << head << "\n";
    cout << "head->prev:\t" << head->prev << "\n";
    cout << "head->next:\t" << head->next << "\n\n";

    cout << "tail:\t\t" << tail << "\n";
    cout << "tail->prev:\t" << tail->prev << "\n";
    cout << "tail->next:\t" << tail->next << "\n\n\n";

    cout << "Linked List printed in reverse order: \n";
    printlinkedList(tail);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

这个:

    nn->next = head;
    nn->prev = NULL;
    nn->next->prev = head;

应该是:

    nn->next = head;
    nn->prev = NULL;
    nn->next->prev = nn;

与此类似:

    nn->next = NULL;
    nn->prev = tail;
    nn->prev->next = tail;

应该是:

    nn->next = NULL;
    nn->prev = tail;
    nn->prev->next = nn;

答案 1 :(得分:1)

您的 insert() 逻辑有缺陷。

当列表为空时,你没事。

但是在 head 前面插入时,您正确设置了 nn->next 以指向旧的 head,但是您随后设置了旧的 head 的 { {1}} 指向旧的 prev(即指向自身)而不是新的 head

当在 nn 之后插入时,您正确设置了 tail 以指向旧的 nn->prev,但是您随后设置了旧的 tail 的 {{1 }} 指向旧的 tail(即指向自身)而不是新的 next

这应该可以解决它:

tail