在双链接列表中排序插入

Sorted Insert in doubly linked list

本文关键字:排序 插入 列表 链接      更新时间:2023-10-16

我正在使用结构体ListItem创建一个双链表,该结构体具有prevnext指针以及类型为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 != NULLhead->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!

重新构造代码。把你的算法写在纸上,看看它在不同情况下应该做什么(列表中没有元素,列表中有一个元素,两个或多个元素,项目很小,项目最大,或者项目介于两者之间)。如果你在纸上写对了,就用代码写下来。

编辑:提示:我想列表之前已经排序了。列表元素应该具有什么属性,您希望在该属性之前插入新项?你怎么能找到它?