2975: 我的编号


时间限制: 1 Sec   内存限制: 128 MB

提交: 42  

解决: 15


题目描述


建立一个学生链表,每个链表结点含有学生的基本信息,编号和姓名。现在n个学生站成一列,根据学生姓名查找学生的编号。

请将代码补充完整,只需提交补充部分。

请用C++方式提交

C++代码:
#include <iostream>
#include <string.h>
using namespace std;
struct student
{
int number;
char name[20];
student *next;
};
student *createlist(int n)
{
int i;
student *head=NULL;
student *p=NULL;
head=new student;
head->next=NULL;
p=head;
cin>>p->number>>p->name;
for(i=1;i<n;i++)
{
p->next=new student;
p=p->next;
p->next=NULL;
cin>>p->number>>p->name;
}
return head;
}

void searchstu(student *head,char *str)
{
student *current;
current=head;
while(current!=NULL)
{
if(!strcmp(current->name,str))
{
cout<<current->number<<endl;
break;
}
/*
补充部分,当前结点后移
*/
}
}

void destroy(student *head)
{
student *p;
p=head;
while(head!=NULL)
{
p=head;
head=head->next;
delete p;
}
}

int main()
{
int n;
char str[20];
student *head;
cin>>n;
head=createlist(n);
cin>>str;
searchstu(head,str);
destroy(head);
return 0;
}

输入


第1行输入一个n,表示n个学生;
第2行到第n+1行,每行输入一个学生的编号和姓名,以空格隔开;
最后1行,输入要查找的学生姓名。


输出


要寻找学生的编号


样例输入

5
1001 tom
1002 bob
1003 mike
1006 daming
1007 xiaohong
tom

样例输出

1001

你  离  开  了  ,  我  的  世  界  里  只  剩  下  雨  。  。  。

#include <iostream>
#include <string.h>
using namespace std;
struct student
{
int number;
char name[20];
student *next;
};
student *createlist(int n)
{
int i;
student *head=NULL;
student *p=NULL;
head=new student;
head->next=NULL;
p=head;
cin>>p->number>>p->name;
for(i=1; i<n; i++)
{
p->next=new student;
p=p->next;
p->next=NULL;
cin>>p->number>>p->name;
}
return head;
}
void searchstu(student *head,char *str)
{
student *current;
current=head;
while(current!=NULL)
{
if(!strcmp(current->name,str))
{
cout<<current->number<<endl;
break;
}
current=current->next;
}
}
void destroy(student *head)
{
student *p;
p=head;
while(head!=NULL)
{
p=head;
head=head->next;
delete p;
}
}
int main()
{
int n;
char str[20];
student *head;
cin>>n;
head=createlist(n);
cin>>str;
searchstu(head,str);
destroy(head);
return 0;
}