数据结构中的关于拉链的举例

 数据结构中的关于拉链的举例

作者:andyhou   时间:2008年4月20日

  这几天在复习数据结构没事编程练习写点东西。好久没动手有点生疏了。呵呵!!

    在数据结构中有很多的地方都涉及都拉链来解决问题。虽然我们每个人对这个很熟悉。但是也有很多人看似觉得很简单。就是从一个数组中拉一条链出来存储一些数据,但是到了真正实现的时候却不知道怎么下手,似乎也觉得很麻烦,而且写出来的程序错误很多。对指针的控制也不知道怎么下手。我自己写的这个程序程序很多的需要拉链的地方都可以模仿的使用。

程序说明:这个程序是把所输入的数据的个位数都存放在一个基数相同位置拉出来的地方

        并且对这些数据的查找和打印。程序很容易理解所以没有什么注释应该很

        容易看懂。

 

#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个数字:
12354
1254
547
457
71
2566
47
235
146
149
输入你要查找的数据:
100
不在系统中!:
输出数据
0
1 --71
2
3
4 --12354 --1254
5 --235
6 --2566 --146
7 --547 --457 --47
8
9 --149


程序结束

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值