【发布时间】:2021-02-19 16:43:45
【问题描述】:
我正在编写代码,该代码采用未排序元素的列表并将它们排序为双向链表。该代码在大多数情况下都有效,可以将元素添加到列表的开头和结尾,但是由于某种原因,如果添加的第一个元素将保留在头部(按字母顺序排列的最高元素)头部的地址,这超出了我的范围和 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;
}
【问题讨论】:
-
您是否有理由不为此使用标准的
std::list容器?它为你实现了一个双链表。 -
我将添加到 OP 但不使用 C++ 类。