程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> C++雙向循環鏈表的操作與實現

C++雙向循環鏈表的操作與實現

編輯:關於C++

雙向循環鏈表的操作與實現……

網上關於這方面的挺多,由於自己以前上課沒好好學數據結構,現在重新認識數據結構,以下是自己寫的基於C++的雙向循環鏈表的創建及其一些操作與實現(於VC下通過),沒用模板,

也沒用類,所以比較適合有一點C++語言基礎入門者,但可移植不夠。有什麼bug的話,歡迎指出。

或有什麼問題也可以聯系我。

made by virgil (2009.2.8)

MSN:[email protected]

#include <iostream>
#include <cstdlib>
using namespace std;
  int N=10;
struct Node
{
char name[20];
Node *llink,*rlink;
};
  Node* Create(int n)
{
Node *h,*p,*s; //h:頭結點,p:下一結點,s:當前結點
int i;
if((h=new Node)==NULL)
{
cout<<"分配內存失敗..."<<endl;
}
h->name[0]=0;
h->llink=NULL;
h->rlink=NULL;
p=h;
for (i=0;i!=n;++i)
{
if((s=new Node)==NULL)
{
cout<<"分配內存失敗..."<<endl;
}
p->rlink=s;
cout<<"請輸入第"<<i+1<<"個人的姓名:";
cin>>s->name;
s->llink=p;
s->rlink=NULL;
p=s;
}
s->rlink=h;
h->llink=s;
return h;
}
Node* Search(Node* h,const char* name)
{
Node *p=h->rlink;
for (int i=0;i!=N;++i)
{
if (strcmp(p->name,name)==0)
{
return p;
}
p=p->rlink;
}
return p;
}
void Insert(Node *p)
{
Node *s=new Node;
cout<<"請輸入要插入的姓名:";
cin>>s->name;
Node *r=p->rlink; //結點示意 p->s->r(s為插入的結點)
p->rlink=s;
s->llink=p;
r->llink=s;
s->rlink=r;
++N;
}
void Delete(Node *p)
{
Node *l=p->llink; //結點示意 l->p->r (p為要刪除的結點)
Node *r=p->rlink;
l->rlink=r;
r->llink=l;
delete p;
--N;
}
void Display(Node *h)
{
Node *p;
p=h->rlink;
for (int i=0;i!=N;++i)
{
cout<<"第"<<i+1<<"個人的姓名:"<<p->name<<endl;
// delete p;
p=p->rlink;
}
}
  int main()
{
Node *head,*pSearch;
int number=N;
char strName[20];
head=Create(number);
cout<<endl;
  cout<<"你創建的結構如下:"<<endl;
Display(head);
cout<<endl;
//查找並插入...
cout<<"請輸入你要查找的人的姓名:";
cin>>strName;
pSearch=Search(head,strName);
cout<<"你所要查找的人的姓名是: "<<pSearch->name<<endl;
cout<<endl;
Insert(pSearch);
cout<<"插入後的結果如下:"<<endl;
Display(head);
cout<<endl;
  //查找並刪除...
cout<<"輸入你要刪除的結點: ";
cin>>strName;
pSearch=Search(head,strName);
Delete(pSearch);
cout<<"刪除後的結果如下:"<<endl;
Display(head);
cout<<endl;
return 0;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved