(C语言)我写了一个关于链表的代码,看看有什么地方要改的么?

代码如下:
#include"stdio.h"
#include"stdlib.h"
#include"windows.h"
//#define MUN 4
//#define SEC 5
#define NAM 20
#define SEX 4
void print(struct student* head);
struct student
{
int munber;
int sec;
char name[NAM];
char sex[SEX];
char end;
student *next;
};
struct student *head=NULL;
struct student *p1,*p2;
void enter()
{
printf("请输入学号:");
scanf_s("%d",&p1->munber);
printf("请输入成绩:");
scanf_s("%d",&p1->sec);
fflush(stdin);
printf("请输入姓名:");
gets_s(p1->name);
fflush(stdin);
printf("请输入性别:");
gets_s(p1->sex);
fflush(stdin);
printf("是否继续输入?(按“Y“继续,其他键停止输入)");
p1->end=getchar();
fflush(stdin);
printf("===================================================\n");
}
int main(void)
{
system("color F0");
p1=(student*)malloc(sizeof(student));
head=p1;
p2=p1;
enter();
p1->next=NULL;
while(p1->end=='Y'||p1->end=='y')
{
p2=p1;
p1=(student*)malloc(sizeof(student));
enter();
p2->next=p1;
}
p1->next=NULL;
print(head);
return 0;
}
void print(struct student *head)
{
struct student *temp;
temp=head;
printf("学号\t姓名\t成绩\t性别\t\n");
while(temp!=NULL)
{
printf("%d\t%s\t%d\t%s\n",temp->munber,temp->name,temp->sec,temp->sex);
temp=temp->next;
}
}
补充:
请问怎么删除节点,插入节点,和修改节点呢?头节点该怎么设计才能实现这些呢?

你这个单向线性链表,要删除节点是很简单的,从header顺序遍历,记录上一个节点,当前节点,当前节点为要删除的节点时,上一个节点->next = 当前节点->next; delete 当前节点;

插入节点和删除也是同理,你肯定要插入在某个节点之前,所以也是从头节点顺序遍历,记录上一个节点,当前节点,当前节点为你要插入再它之前的节点时,上一个节点->next = 要插入的节点; 要插入的节点->next = 当前节点;

对容器的设计,可以参考下stl的做法或者是MFC的CList CArray CMap等容器的做法,容器相关的东西,面向对象,模板化,重载运算符,都用起来,就不错了。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-08-17
你首先明白链表的分类一般为: 是否有头、 是否双向、 是否循环、 是否有序。

这样可以分为16种链表, 又双向链表一般为循环的, 所以还有12种链表供你选择,而且都可以实现你要得功能。
我觉得你先学会封装链表吧。
相似回答
大家正在搜