在双链接列表中排序插入
Sorted Insert in doubly linked list
我正在使用结构体ListItem
创建一个双链表,该结构体具有prev
和next
指针以及类型为T的值。
我做得对吗?
当我运行主代码时,我只能在显示屏上看到1、15和16。
template <class T>
void List<T>::insertSorted(T item)
{
ListItem<T> *node=new ListItem<T>(item);
if (head==NULL)
{
head=node;
}
else if (head!=NULL)
{
T c,d;
ListItem<T> *temp,*temp2;
temp=head;
c=temp->value;
int count=0;
while (temp->next!=NULL)
{
if (temp->prev!=NULL)
temp2=temp->prev;
if (c>item && item>temp2->value)
{
if (temp->prev!=NULL)
{
temp2->next=node;
node->prev=temp2;
node->next=temp;
temp->prev=node;
count++;
}
else if (temp->prev==NULL)
{
head=node;
head->next=temp;
count++;
}
}
temp=temp->next;
c=temp->value;
}
if (temp->value<item) //comparison with last temp
{
temp->next=node;
node->prev=temp;
}
else if (temp->value>item)
{
temp2=temp->prev;
temp2->next=node;
node->prev=temp2;
node->next=temp;
temp->prev=node;
}
}
}
int main()
{
List<int> Mylist;
for (int i=16;i>0;i--)
{
Mylist.insertSorted(i); //insertion should be in ascending order according
//to my fnction
}
Mylist.printList(); //prints the whole linked list
system("PAUSE");
return 0;
}
不,您正在做的是UB。给定head != NULL
和head->next != NULL
,这意味着列表中至少有两项:
else if (head!=NULL)
{
T c,d;
ListItem<T> *temp,*temp2; //temp2 points to nirvana
temp=head; //temp is head
c=temp->value;
int count=0;
while (temp->next!=NULL) //head->next != NULL, so enter the loop
{
if (temp->prev!=NULL) //head->prev is NULL...
temp2=temp->prev; //.. so temp2 continues to point into nirvana
if (c>item && item>temp2->value) //take nirvana's value. OUCH!
重新构造代码。把你的算法写在纸上,看看它在不同情况下应该做什么(列表中没有元素,列表中有一个元素,两个或多个元素,项目很小,项目最大,或者项目介于两者之间)。如果你在纸上写对了,就用代码写下来。
编辑:提示:我想列表之前已经排序了。列表元素应该具有什么属性,您希望在该属性之前插入新项?你怎么能找到它?
相关文章:
- 这是插入排序的正确实现吗?
- 使用列表 STL 递归进行插入排序
- 列表 iter 不取消引用 使用列表进行插入排序
- 如何使插入排序更快?
- 插入排序的最小交换
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 插入按降序排序
- std::为插入和排序设置不同的比较器
- 双链表C++上的插入排序
- 如何在插入排序中使用 replace() 使语句变得不必要
- 如何将标准::矢量插入具有自定义排序功能的 std::set 中
- 在排序链表中插入结构并将其写入二进制文件
- 映射C++按值排序和插入元素
- 已排序插入到链表中
- 如果第一个相同,则通过按秒排序插入 STL 对集
- 寻找c++快速排序/插入排序组合中的错误
- 如果边没有按权值排序插入队列,0-1 BFS是否会产生正确的答案?
- c++选择排序插入方法和私有变量
- 在双链接列表中排序插入