正文

数据结构中的关于拉链的举例2008-04-11 00:55:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/andyhou/34063.html

分享到:

               数据结构中的关于拉链的举例 作者:andyhou   这几天在复习数据结构没事编程练习写点东西。好久没动手有点生疏了。呵呵!!     在数据结构中有很多的地方都涉及都拉链来解决问题。虽然我们每个人对这个很熟悉。但是也有很多人看似觉得很简单。就是从一个数组中拉一条链出来存储一些数据,但是到了真正实现的时候却不知道怎么下手,似乎也觉得很麻烦,而且写出来的程序错误很多。对指针的控制也不知道怎么下手。我自己写的这个程序程序很多的需要拉链的地方都可以模仿的使用。 程序说明:这个程序是把所输入的数据的个位数都存放在一个基数相同位置拉出来的地方         并且对这些数据的查找和打印。程序很容易理解所以没有什么注释应该很         容易看懂。   #include <iostream>using namespace std; const int  r=10;//基数const int N=20; //设置数组长度 struct Node{ int element; Node *next;}; //初始化void Init(struct Node *Array,int r){ for(int i=0;i<r;i++) {  Array[i].element=i;  Array[i].next=NULL; }} void Insert(struct Node *Array,int &item){ int R; struct Node *temp=new struct Node; struct Node *T; temp->element=item; R=item%10; if(Array[R].next==NULL)  {    Array[R].next=temp;    temp->next=NULL;  } else {   T=Array[R].next;   while(T->next!=NULL)   {    T=T->next;   }   T->next=temp;   temp->next=NULL;  }    } bool search(struct Node* Array,int &item){ int R=item%10; struct Node* T=&Array[R]; while(T->next!=NULL&&T->next->element!=item)  T=T->next; return (T->element==item);} void print(struct Node* Array){ for(int i=0;i<r;i++) {  cout<<Array[i].element<<" ";   while(Array[i].next!=NULL)   {    cout<<"--"<<Array[i].next->element<<" ";     Array[i].next=Array[i].next->next;   }   cout<<endl; }} void del(struct Node *Array){ struct Node* temp; for(int i=0;i<r;i++) {   while(Array[i].next!=NULL)   {    temp=Array[i].next;    delete Array[i].next;    Array[i].next=temp->next;   } } delete[] Array;} int main(){ int it,item; struct Node *Array=new struct Node[r]; Init(Array,r); cout<<"在输入10个数字:"<<endl; for(int j=0;j<10;j++) {  cin>>it;  Insert(Array,it); } cout<<"输入你要查找的数据:"<<endl; cin>>item; if(search(Array,item)) {  cout<<"在系统中"<<endl; } else {  cout<<"不在系统中!:"<<endl; } cout<<"输出数据"<<endl; print(Array); del(Array); return 0;} 测试数据举例显示: 在输入10个数字:12354125454745771256647235146149输入你要查找的数据:100不在系统中!:输出数据01 --71234 --12354 --12545 --2356 --2566 --1467 --547 --457 --4789 --149 程序结束。

阅读(3472) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册