有一链式结构,定义如下 :
struct stu{
char name[20];
int no;
struct stu *next;
};
创建一个函数create(),实现无头结点的链表,有m个结点,函数的返回值为链表的头指针。
函数接口定义:
在这里描述函数接口。例如:
struct stu * create()
在这里解释接口参数。在函数中输入m,及m行数据,完成链表的创建。
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
#include <stdio.h>
#include <stdlib.h>
struct stu{
char name[20];
int no;
struct stu *next;};
struct stu * create();
void show(struct stu *p){
while(p){
printf("%s %d\n",p->name,p->no);
p=p->next;
}
}
int main()
{
struct stu *p=NULL;
p=create();
show(p);
return 0;
}
/* 请在这里填写答案 */
输入样例:
在这里给出一组输入。例如:
2
liming 23
maming 35
输出样例:
在这里给出相应的输出。例如:
liming 23
maming 35
代码:
struct stu* create()
{
int m = 0;
scanf("%d", &m);
struct stu* head = NULL;
struct stu* tail = NULL;
for (int i = 0; i < m; i++)
{
struct stu* newNode = (struct stu*)malloc(sizeof(struct stu));
scanf("%s %d", newNode->name, &newNode->no);
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
}
return head;
}
注意:
1.newNode->name是数组名即是数组的地址
scanf("%s %d", newNode->name, &newNode->no);
2.在将新节点插入链表时,需要确保新节点的next指针指向NULL,以便正确地连接新节点到链表的末尾。在这个特定的情况下,我们在每次创建新节点后,都将新节点的next指针设置为NULL,这是为了确保新节点在插入链表时正确连接到链表的末尾。
scanf("%s %d", newNode->name, &newNode->no);
newNode->next = NULL;
3.
判断链表是否为空,如果是空链表,则将head和tail指向新节点。
如果不是空链表,则将当前tail节点的next指针指向新节点,然后将tail指针移动到新节点上。
if (head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
本题要求实现一个将输入的学生成绩组织成单向链表的简单函数。
函数接口定义:
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
代码:
void input()
{
struct stud_node* newNode;
head = tail = NULL;
while (1)
{
newNode = (struct stud_node*)malloc(sizeof(struct stud_node));
scanf("%d", &newNode->num);
if (newNode->num == 0)
{
free(newNode);
break;
}
scanf("%s %d", newNode->name, &newNode->score);
newNode->next = NULL;
if (head == NULL)
{
head = tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
}
}
if (newNode->num == 0)
{
free(newNode);
break;
}
一定要记住