实验03-顺序表-
题目描述
1.问题描述
给出初始数据,实现单链表的定义、创建、输出。
2.算法
单链表结点的存储结构包含两部分:数据、下一结点指针。
单链表的创建:输入n个数据e,若数据e不在单链表中,为数据e分配结点,并插入在单链表的尾部;若单链表中已有数据e,则不做任何操作。
单链表的输出:从头至尾遍历单链表,输出每个结点的元素值。
注:程序不可定义任何数组,否则不计成绩。
要求:查找定义子函数:int Find(Node *H,int e) //找到e返回1,找不到返回0。其中Node为链表结点结构体名,H为链表头指针。
输入
第一行:测试次数t
对每组测试数据,格式如下:
数据个数n 数据1 数据2 数据3 … 数据n
输出
对每组测试数据,输出链表中元素个数和单链表中的全部数据。
输入样例
2
5 2 3 5 7 3
6 1 2 10 0 1 5
4 2 3 5 7
5 1 2 10 0 5
单链表的定义、创建、输出
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
int Find(node *H,int e)//查找有无重复数据
{
while(H->next)
{
H=H->next;
if(H->data==e)
{
return 1;
break;
}
}
return 0;
}
void create(node *H,int &n)//尾插法
{
H->next=NULL;
struct node *p=H,*s;
int e,i,m=0;
for(i=0;i<n;i++)
{
cin>>e;
if(Find(H,e)==0)
{
s=new node;s->next=NULL;s->data=e;
p->next=s;
p=s;
}
else
m++;
}
n=n-m;//单链表长度
}
int main()
{
int t,n;
cin>>t;
while(t--)
{
node* L=new node;
cin>>n;
create(L,n);
cout<<n<<" ";
while(L->next)//输出
{
L=L->next;
cout<<L->data<<" ";
}
cout<<"\n";
delete L;
}
return 0;
}