精品理论电影在线_日韩视频一区二区_一本色道精品久久一区二区三区_香蕉综合视频

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

發布時間:2011-08-29 共1頁

  // 雙向循環鏈表的操作與實現...
  // 網上關于這方面的挺多,由于自己以前上課沒好好學數據結構,現在重新認識數據結構,
  // 以下是自己寫的基于C++的雙向循環鏈表的創建及其一些操作與實現(于VC下通過),沒用模板,
  // 也沒用類,所以比較適合有一點C++語言基礎入門者,但可移植不夠.有什么bug的話,歡迎指出。
  // 或有什么問題也可以聯系我。
  // made by virgil (2009.2.8)
  // MSN:hangyu_628@hotmail.com)
  #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;
  }

百分百考試網 考試寶典

立即免費試用