一个双向链表的小程序
设计了一个双向链表的小程序,但总觉得不够简洁,难道每个数据非要两个地址?有什么更好的办法?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;
}
}