题目描述
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
代码实现:如下
//
// Created by HP on 2018/3/9.
//
#include <iostream>
using namespace std;
struct node{
int num;
node *next;
};
int c;
int find(node *head,int key)
{
node *finder=head->next;
while(finder!=NULL){
if(finder->num==key)//如果想要插入的数据已经在链表中
return 1;
finder=finder->next;
}
return 0;
}
void CreateList(node *head)
{
node *tail=head;
int data;
int n,i;
cin>>n;
for(i=0;i<n;i++){
cin>>data;
if(find(head,data)==0){
node *s=new node;//创建新的节点
s->num=data;
s->next=NULL;
tail->next=s;//将新结点插入链表中
tail=s;
c++;
}
}
}
void ShowList(node *head)
{
cout<<c<<" ";
node *display=head->next;
while(display){
c--;
cout<<display->num<<" ";
display=display->next;
}
cout<<endl;
}
int main()
{
int t;
cin>>t;
while(t--){
c=0;
node *head=new node;
head->next=NULL;
CreateList(head);//创建
ShowList(head);//输出
}
return 0;
}