题目描述
1.问题描述
给出初始数据,实现单链表的定义、创建、查找。假设单链表中的结点计数从1开始。
2.算法
单链表结点的存储结构包含两部分:数据、下一结点指针。
单链表的创建:依次为输入的数据分配结点,并按序链接起来。
单链表结点个数L(也称单链表表长L):从头至尾遍历单链表,对结点进行计数。
单链表的查找:给出位置i,若第i个结点存在(1<=i<=L),返回结点地址;否则,返回NULL。
要求查找子函数定义为:Node *Find(Node *H,int i)
//若i的值在1...单链表长L之间,返回第i个结点的地址;否则返回空指针NULL。其中Node为链表结点结构体名,H为链表头指针。输入
每个样本分2行:
第一行:第一个数字n表示样本数目,其后跟n个样本。
第二行:查找测试次数m 后跟m个待查找的位置。
输出
第一行:单链表创建后,输出链表中元素个数和单链表中的全部数据。
第二行到第n+1行,对每个查找位置,若结点存在,输出结点数据;否则输出error。
样例输入
6 1 2 3 4 5 6
4 0 2 10 6
样例输出
6 1 2 3 4 5 6
error
2
error
6
代码实现:
// // Created by HP on 2018/3/9. // #include <iostream> using namespace std; struct node{ int num; node *next; }; int n; void CreateList(node *head) { node *tail=head; int data; int i; for(i=0;i<n;i++){ cin>>data; node *s=new node;//创建新的节点 s->num=data; s->next=NULL; tail->next=s;//将新结点插入链表中 tail=s; } } void ShowList(node *head) { cout<<n<<" "; node *display=head->next; while(display){ cout<<display->num<<" "; display=display->next; } cout<<endl; } void search(node *head,int dn) { node *display=head->next; int count=1; while(count!=dn){ count++; display=display->next; } cout<<display->num<<endl; } int main() { int t; cin>>n; node *head=new node; head->next=NULL; CreateList(head);//创建 ShowList(head);//输出 cin>>t; while(t--){ int dn; cin>>dn; if(dn<=0||dn>n) cout<<"error"<<endl; else search(head,dn); } return 0; }