【发布时间】:2020-11-12 08:54:06
【问题描述】:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Node{
int data;
Node* next;
Node* prev;
};
Node* head;
void display(){
Node* temp = head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
void insert(int value){
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = value;
temp->prev = NULL;
temp->next = NULL;
if(head==NULL){
head = temp;
}
else{
Node* t = head;
while(t->next!=NULL){
t = t->next;
}
t->next = temp;
temp->next = NULL;
temp->prev = t;
}
}
void insertAtFirst(int value){
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = value;
temp->prev = NULL;
temp->next = head;
head->prev = temp;
head = temp;
}
void sortedInsert(int value){
Node* curr = head;
while(curr->next!=NULL)
curr = curr->next;
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = value;
if(head==NULL || temp->data < head->data){
temp->prev = NULL;
temp->next = head;
head->prev = temp;
head = temp;
}
else if(head->next!= NULL && temp->data >= head->data){
Node* pred = head;
while(temp->data > pred->data){
pred = pred->next;
}
pred->prev->next = temp;
temp->prev = pred->prev;
temp->next = pred;
pred->prev = temp;
}
else if(curr->next==NULL){
curr->next = temp;
temp->prev = curr;
temp->next = NULL;
}
}
int main()
{
insert(10);
insert(20);
insert(25);
insert(35);
insertAtFirst(1);
insertAtFirst(29);
sortedInsert(30);
sortedInsert(40);
//1 10 20 25 29 30 35 40
display();
return 0;
}
我想我可能已经实现了双向链表。但是,我面临的问题是,当我尝试输入一个数据大于最后一个节点的现有数据的节点时,它不会保存。我使用的逻辑可能有问题 - 查找了一些以前的答案,但未能解决问题。
【问题讨论】:
-
如果
if(curr->next==NULL)为假会怎样?您是否尝试过使用调试器? -
@AlanBirtles 不可能,
curr是列表中的最后一个节点。 -
为什么你会调用最后一个元素
curr,如果条件永远不会为假,为什么它存在? -
@AlanBirtles - 我想我只想让 curr 指向一个 curr->next 指向 NULL 的节点,这样我就可以简单地将 temp 链接到 curr->next。我不明白为什么这不起作用。逻辑对我来说似乎没问题。
-
您的
while (temp->data > pred->data)循环不检查 null。您是否尝试过使用调试器找出您的逻辑出错的地方?
标签: c++ data-structures doubly-linked-list