标题:一个双向链表的小程序
只看楼主
tigerdown
Rank: 1
等 级:新手上路
帖 子:63
专家分:3
注 册:2017-8-21
结帖率:69.23%
 问题点数:0 回复次数:0 
一个双向链表的小程序
设计了一个双向链表的小程序,但总觉得不够简洁,难道每个数据非要两个地址?有什么更好的办法?



int main()
   {
   linklist li;                 //make linked list

   li.SetUpFirstItem(25);       //add four items to list
   li.additem(36);
   li.additem(49);
   li.additem(64);
   li.SetUpLastItem();
                                //Display link list in two directions
   cout<<"Display link form left to right:"<<endl;
   li.displayByFirst();
   cout<<endl;
   cout<<"Display link form right to left:"<<endl; ;
   li.displayByLast();

   getch();
   return 0;
   }
//--------------------------------------------------------------------------
void linklist::SetUpFirstItem(int FirstItem)
   {
   link* newlink = new link;    //make a new link >>>add1
   newlink->data = FirstItem;   //give it data to first link
                                //Last = NULL
   newlink->NextToRight = Last;
   Last = newlink;              //now Last points to this
   First = newlink;             //now first points to this and keep it
   NextNode = newlink;          //now NextNode points to this
   }
//---------------------------------------------------------------------------
void linklist::additem(int d)         //add data item
   {
   link* newlink = new link;          //make a new link >>>add2
   newlink->data = d;                 //give it data  >>>d2
   newlink->NextToRight = Last;       //it points to next link >>>Last=add1
   Last = newlink;                    //now first points to this>>>Last=add2

   NextNode->NextToLeft = Last ;      //NextNode=add1, Last=add2
   NextNode = newlink;                //NextNode=add2
   }
//---------------------------------------------------------------------------
void linklist::SetUpLastItem()
{
 Last->NextToLeft = NULL;
}
//---------------------------------------------------------------------------
void linklist::displayByLast()
   {
   link* current = Last;              //set ptr to last link
   while( current != NULL )           //quit on last link
      {
      cout << current->data <<", ";  //print data
                                     //Move to next pointer(NextToRight)
      current = current->NextToRight;
      }
   }
//----------------------------------------------------------------------------
void linklist::displayByFirst()
   {
   link* current = First;             //set ptr to first link
   while( current != NULL )           //quit on last link
      {
      cout << current->data <<", ";  //print data
                                     //Move to next pointer(NextToLeft)
      current = current->NextToLeft;
      }
   }


搜索更多相关主题的帖子: data link current first cout 
2021-06-01 19:59



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-505916-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.504404 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved