单链表
建立一个单链表,并将其输出?出现的问题是:只能输入一个节点的数据,不能全部输入
#include<stdio.h>
#include<stdlib.h>
#define n 5
struct student{
int num;
char name;
char sex;
intage;
struct student *next;
};
struct student *jianli(struct student *head)
{
struct student *p,*q;
head=(struct student *)malloc(sizeof(struct student));
p=head=NULL;
int i;
for(i=0;i<n;i++)
{
q=(struct student *)malloc(sizeof(struct student));
q->next=NULL;
printf("请输入学号,姓名,性别,年龄\n");
scanf("%d %s %s %d",&(q->num),q->name,q->sex,&(q->age));
q->next=p->next;
p->next=q;
p=q;
}
p->next=NULL;
return head;
}
struct student *shuchu(struct student *head)
{
struct student *p,*q;
int x;
p=head;
q=p->next;
printf("请输入一个年龄");
scanf("%d",&x);
while(q!=NULL)
{
if(q->age==x)
p->next=q->next;
else
{
p=q;
q=q->next;
}
}
return head;
}
int main()
{ struct student *head,*p,*q;
jianli(head);
shuchu(head);
q=head->next;
while(q!=NULL)
{
printf("%d %10s %10s %d\n",q->num,q->name,q->sex,q->age);
q=q->next;
}
} 你这个是循环输入,每次当然只能输入一组。还有一个问题你没有释放内存 #include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#define n 5
struct student{
int num;
struct student *next;
};
struct student *jianli(struct student *head)
{
struct student *p,*q;
for(int i=0;i<n;i++)
{
q=(struct student *)malloc(sizeof(struct student));
q->next=NULL;
printf("请输入学号,姓名,性别,年龄\n");
scanf("%d",&(q->num));
if (head == NULL)
{
head= q;
p = head; //用作数据链接
}
else
{
p->next = q;
p = q;
}
}
return head;
}
void shuchu(struct student *head)
{
/*struct student *p,*q;
int x;
p=head;
q=p->next;
printf("请输入一个年龄");
scanf("%d",&x);
while(q!=NULL)
{
if(q->age==x)
p->next=q->next;
else
{
p=q;
q=q->next;
}
}*/
struct student *p;
while(head!=NULL)
{
p = head;
printf("%d\n",head->num);
head = head->next;
free(p); //
p = nullptr;
}
}
int main()
{
struct student *head = NULL,*q = NULL;
head = jianli(head);
shuchu(head);
system("pause");
}
页:
[1]