简单的链表问题,有一点小问题,求大佬看看怎么解决
问题;我的代码(用的软件是codeblocks):
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <malloc.h>
//定义结构体
struct Student
{
char num[20];
char name[20];
int age;
struct Student *next;
};
//函数声明
void setup(struct Student **head);
void output(struct Student *head);
void dele(struct Student **head);
void insert2(struct Student **head);
void insert3(struct Student **head);
//主函数
int main()
{
struct Student *head=NULL;
int x;
printf("输入1:建立学生信息表;\n输入2:在指定学生之前插入新的学生信息;\n输入3:在学生表尾部插入新的学生信息;\n输入4:输出所有学生信息;\n输入5:删除指定的学生信息;\n");
do
{
printf("\n请输入你需要使用的功能:");
scanf("%d",&x);
switch(x)
{
case 0 :
break;
case 1 :
setup(&head);
break;
case 2:
insert2(&head);
break;
case 3:
insert3(&head);
break;
case 4 :
output(head);
break;
case 5 :
dele(&head);
break;
default :
printf ("选择错误!\n");
break;
}
//建立动态链表(指针操作)
void setup(struct Student **head)
{
struct Student *p = (struct Student*)malloc(sizeof(struct Student));
struct Student *stu=NULL;
printf("num:");
scanf("%s",(p->num));
printf("name:");
scanf("%s",(p->name));
printf("age:");
scanf("%d",&p->age);
p->next=NULL;
if(*head == NULL)
{
*head = p;
}
else
{
stu = *head;
while(stu->next != NULL)
{
stu = stu->next;
}
stu->next = p;
}
}
//在链表开头或者中间插入节点(指针操作)
void insert2(struct Student **head)
{
struct Student *p1,*p2;
p1=*head;
p2=p1->next;
char arri[20];
printf("输入要插入的学生位置的学号:");
scanf("%s",arri);
struct Student *p=(struct Student*)malloc(sizeof(struct Student));
printf("输入要插入的学生信息:\n");
printf("num:");
scanf("%s",(p->num));
printf("name:");
scanf("%s",(p->name));
printf("age:");
scanf("%d",&p->age);
p->next=NULL;
while(p2!=NULL)
{
if(strcmp(arri,p2->num)==0)
{
p1->next=p;
p->next=p2;
}
p1=p2;
p2=p2->next;
}
output(*head);
}
//在链表尾插入节点(指针操作)
void insert3(struct Student **head)
{
struct Student *p = (struct Student*)malloc(sizeof(struct Student));
printf("输入要插入的学生信息:\n");
printf("num:");
scanf("%s",(p->num));
printf("name:");
scanf("%s",(p->name));
printf("age:");
scanf("%d",&p->age);
p->next=NULL;
struct Student *p1;
while(p1->next!=NULL)
{
p1=p1->next;
}
p1->next=p;
output(*head);
}
//输出整个链表(把整个表传过来)
void output(struct Student *head)
{
while(head != NULL)
{
printf("学号:%s;姓名:%s;年龄:%d\n",head->num,head->name,head->age);
head=head->next;
}
}
//删除指定的节点
void dele(struct Student **head)
{
char arr1[20];
struct Student *p1 = NULL;
struct Student *p2 = *head;
printf("请输入要删除的学生的学号:\n");
scanf("%s",arr1);
while(p2!=NULL)
{
if(p1==NULL&&strcmp(arr1,p2->num)==0)
{
*head = p2->next;
free(p2);
break ;
}
else if(strcmp(arr1,p2->num)==0)
{
p1->next = p2->next;
free(p2);
break ;
}
p1=p2;
p2=p2->next;
}
output(*head);
}
其中建立、输出和删除可以正常进行:
错误:
这里的功能2(在开头位置或中间插入)无法插入;
功能3(在表尾插入)会直接结束。
这两个插入怎么解决呢?
(这个网站没用过,我怕传输有问题,下面是完整的)
第十、十一周实验课练习内容(结构体和链表).zip
(392.48 KB)