问题遇到的现象和发生背景
程序目的给链表插入新的节点
主函数中不知道为什么gets函数没有输入if也没判断就直接进入了insert函数,希望有人能解答帮忙改正一下
遇到的现象和发生背景,请写出第一个错误信息
用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int ID, score;
struct node* next;
};
int main()
{
struct node* creat(struct node* head, int n);
struct node* insert(struct node* head);
void print(struct node* head);
struct node* head = NULL;
int n;
char str[10],a[10]="yes",b[10]="no";
printf("please enter n\n");
scanf_s("%d", &n);
head = creat(head, n);
printf("Do you want to insert a student's score?(enter yes or no)\n");//主函数从这段开始出问题不知道为什么gets函数没有输入if也没判断就直接进入insert函数
gets_s(str);
if ((strcmp(str, a) == 0)||(strcmp(str,b)!=0)) {
head = insert(head);
print(head);
}
}
struct node* creat(struct node* head,int n)//链表的构造
{
struct node* p = NULL, * q = NULL;
int i;
for (i = 1; i <= n; i++) {
q = (struct node*)malloc(sizeof(struct node));
printf("please enter %dth ID score\n", i);
scanf_s("%d %d", &q->ID, &q->score);
q->next = NULL;
if (head == NULL) {
head = q;
}
else {
p->next = q;
}
p = q;
}
return head;
}
struct node *insert(struct node* head)//链表插入新节点的函数(序号是按照小到大排序输入)
{
struct node* y =NULL, * q = NULL,*p=head;
y = (struct node*)malloc(sizeof(struct node));
printf("please enter ID and score of the student\n");
scanf_s("%d %d", &p->ID, &p->score);
if (p->ID > y->ID) { //新节点插入表头之前
head = y;
y->next = p;
}
while (p != NULL && p->ID < y->ID) {
q = p;
p = p->next;
}
if (p != NULL) { //新节点插入表中
q->next = y;
y->next = p;
}
else { //新结点插入表尾
q->next = y;
}
return head;
}
void print(struct node* head)//输出链表
{
struct node *p = head;
while (p != NULL) {
printf("ID:%d score:%d\n", p->ID, p->score);
p = p->next;
}
}