我需要帮助对此双链接列表(C )进行分类
I need help sorting this double linked list (C++)
这就是我到目前为止所拥有的:
void sort(const E &t)
{
DNode<E> *tmp = new DNode<E>(t,NULL,NULL);
if(size==0)
{
cout << "List is empty" << endl;
}
else if(t<=head->element)
{
tmp->element=t;
head->prev = tmp;
tmp->next=head;
head = tmp;
}
else if(t>=tail->element)
{
tmp->element=t;
tail->next = tmp;
tmp->prev=tail;
tail = tmp;
}
curr=tmp;
insert(t);
size++;
}
insert()只是我程序中的另一个函数:
void insert(const E &t)
{
DNode<E> *tmp = new DNode<E>(t,NULL,NULL);
if (size == 0)
{ curr=head=tail=tmp; }
else
{
tmp->next=curr;
tmp->prev=curr->prev;
if (curr->prev) curr->prev->next=tmp;
else { head=tmp; }
curr->prev=tmp;
curr=tmp;
}
size++;
}
它确实编译了,但没有给出正确的结果。我不确定我的错误是什么,我真的需要帮助。任何帮助将不胜感激。
这是我的主要程序中:
one.sort(10);
one.sort(20);
one.sort(30);
one.sort(40);
one.sort(50);
one.sort(60);
one.print();
one.moveToEnd();
one.prev();
one.prev();
one.remove();
one.remove();
one.print();
cout<<endl;
我应该得到这个:
head ==> 10-> 20-> 30-> 30-> 40-> 50-> 60&lt; ==尾巴head ==> 10-> 20-> 50-> 60&lt; ==尾巴
,但我得到了这个:头==> 10-> 20-> 20-> 30-> 30-> 30-> 40-> 40-> 40-> 50-> 50-> 50-> 60-> 60&lt;==尾巴head ==> 10-> 20-> 20-> 30-> 30-> 30-> 40-> 40-> 40-> 60-> 60&lt; ==尾巴
您看到的行为的原因是您缺少其他
这个:
curr=tmp;
insert(t);
size++;
是否在头部或尾巴上添加了一些东西,都将执行。由于您提供的每个条目都会添加到尾巴上,因此每次都会插入两次。如果您尚未将值添加到头部或尾部,则只能致电插入。
如果我正确理解,则应运行curr=tmp;
和size++;
,无论如何,只有插入的呼叫才能在其他块中,我认为。
编辑:
应该看起来像这样:
if(size==0)
{
cout << "List is empty" << endl;
//Need to insert here as well, to add the first value to the list.
insert(t);
}
else if(t<=head->element)
{
tmp->element=t;
head->prev = tmp;
tmp->next=head;
head = tmp;
}
else if(t>=tail->element)
{
tmp->element=t;
tail->next = tmp;
tmp->prev=tail;
tail = tmp;
}
else
{
insert(t);
}
curr=tmp;
size++;
我(Kinda)维护了您的空格使用情况,尽管我发现它有点不寻常。如果"否则"answers"其他"陈述,我通常将相关的''放在同一凹陷级别上,并进一步缩进嵌套块。我认为这是更标准的,但在这里也不是。
希望这会有所帮助:
struct node {
node* next;
node* prev;
Person p;
};
void sort(node* head) {
node* n1;
node* n2;
for(n1 = head; n1->next != head; n1 = n1->next) {
for( n2 = n1->next; n2 != head; n2 = n2->next) {
// swap data here if necessary
}
}
}
用于交换:
X1 = currPtr->previoius;
X2 = currPtr->next->next;
currNext = currPtr->next;
currNext->previous = currPtr->previous;
currPtr->previous = currPtr->next;
currPtr->next = currNext->next;
currNext->next = currPtr;
X1->next = currPtr->previous;
X2->previous = currPtr;
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- 如何在这两个分类的链接列表之间获得开关的位置
- 链接的列表字符串分类问题
- 我一直在尝试递归中编写一个分类的链接列表函数
- 如何插入一个分类的单链接列表中
- 分类指针的列表
- 我需要帮助对此双链接列表(C )进行分类
- 循环访问自定义分类对象的列表