題目:
本題要求實作一個將輸入的學生成績組織成單向鏈表的簡單函式。
函式介面定義:
void input();
該函式利用scanf從輸入中獲取學生的資訊,并將其組織成單向鏈表。鏈表節點結構定義如下:
struct stud_node {
int num; /*學號*/
char name[20]; /*姓名*/
int score; /*成績*/
struct stud_node *next; /*指向下個結點的指標*/
};
單向鏈表的頭尾指標保存在全域變數head和tail中。
輸入為若干個學生的資訊(學號、姓名、成績),當輸入學號為0時結束。
裁判測驗程式樣例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *head, *tail;
void input();
int main()
{
struct stud_node *p;
head = tail = NULL;
input();
for ( p = head; p != NULL; p = p->next )
printf("%d %s %d\n", p->num, p->name, p->score);
return 0;
}
/* 你的代碼將被嵌在這里 */
輸入樣例:
1 zhang 78
2 wang 80
3 li 75
4 zhao 85
0
輸出樣例:
1 zhang 78
2 wang 80
3 li 75
4 zhao 85
答案:(測驗正確,但是用pta交上去之后有一個測驗點是錯誤的)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stud_node
{
int num;
char name[20];
int score;
struct stud_node *next;
}*head,*tail;
void input();
int main()
{
struct stud_node *p;
head=tail=NULL;
input();
for(p=head;p!=NULL;p=p->next)
printf("%d %s %d\n",p->num,p->name,p->score);
return 0;
}
void input()
{
struct stud_node *q;
int score;
char name[20];
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d",&q->num);
while(q->num!=0)
{
scanf("%s %d",name,&score);
strcpy(q->name,name);
q->score=score;
q->next=NULL;
if(head==NULL)
{
head=q;
tail=q;
}
else
{
tail->next=q;
}
tail=q;
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d",&q->num);
}
tail->next=NULL;
}
uj5u.com熱心網友回復:
void input(){
struct stud_node *q;
int score;
char name[20];
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d",&q->num);
if(q->num==0) head=NULL;
else
{
while(q->num!=0)
{
scanf("%s %d",name,&score);
strcpy(q->name,name);
q->score=score;
q->next=NULL;
if(head==NULL)
{
head=q;
tail=q;
}
else tail->next=q;
tail=q;
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d",&q->num);
}
tail->next=NULL;
}
}
考慮輸入的第一個數就是0 ,程式會崩的情況
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/14208.html
標籤:基礎類
上一篇:數學證明2016很神奇: 2016=666+666+666+6+6+6 2016=888+888+88+88+8+8+8+8+8+8+8+8 2016=999+
下一篇:條形碼的相關GB標準
