作者: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
程序结束
本文介绍了一种利用拉链法进行数据存储和检索的方法。通过将数据的个位数作为链表的索引,实现了高效的数据管理和查询功能。文章提供了一个简单的C++程序实例,演示如何插入、查找及打印数据。
1667

被折叠的 条评论
为什么被折叠?



