#include<stdio.h>
#include<stdlib.h>
//建立动态单向链表,结点类型;
typedef struct student{
int no;
int score;
struct student *next;
};
//创建一个链表
struct student *head;
struct student *creat()
{
struct student *p,*q;
int n, i;
printf("how many :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p=(struct student*)malloc(sizeof(struct student));
printf("NO :"); scanf("%d",&p->no);
printf("Score :"); scanf("%d",&p->score);
if(i==0) head = p;
else q->next=p;
q=p;
}
p->next=NULL;
return (head);
}
//输出由表头指针head指向的链表
void print(struct student *head)
{
struct student *p;
p=head;
while(p!=NULL)
{
printf("%d %d/n",p->no,p->score);
p=p->next;
}
}
//函数find由表头指针head指向链表中查找学号等于n的结点
void find(struct student *head)
{
int n;
struct student *p;
printf("enter NO :");
scanf("%d",&n);
p=head;
while(p!=NULL && p->no!=n)
p=p->next;
if(p!=NULL) printf("%d %d /n",p->no,p->score);
else printf(" not find %d student/n",n);
}
//以下函数insert用于有表头指针head指向链表中的第i个结点之后插入一个结点p
struct student *insert(struct student *head)
{
int i,j;
struct student *p,*q;
printf("第 i 个结点 :");
scanf("%d",&i);
p=(struct student*)malloc(sizeof(struct student));// fenpeiyigekongjian gei p 指针
printf("NO :"); scanf("%d",&p->no);//
printf("Score :"); scanf("%d",&p->score);//建了个新结点
if(i==0)
{
p->next=head;
head=p;
}
else
{
q=head;
for(j=1;j<i;j++) q=q->next;//找到第i个结点,让q指向
if(q!=NULL)
{
p->next=q->next;
q->next=p;
}
else printf("i too biger/n");
}
return (head);
}
//以下delete函数用于表头指针head指向的链表中删除第 i个结点
struct student *delet(struct student *head)
{
int i,j;
struct student *p,*q;
printf("enter i (i>0) :");
scanf("%d",&i);
if(i==1)
{
p=head;
head=head->next;
free(p);
}
else
{
q=head;
for(j=1;j<i-1;j++) q=q->next;
if(q!=NULL)
{
p=q->next;
q->next=p->next;
free(p);
}
else printf("i too biger/n");
}
return (head);
}
//以下由flist函数释放有表头head指向的链表
void flist(struct student *head)
{
struct student *p;
while(head !=NULL)
{
p=head;
head=head->next;
free(p);
}
printf("nothing/n");
}
int main()
{
struct student *head;
head=creat();
print(head);
find(head);
head=insert(head);
print(head);
head=delet(head);
print(head);
flist(head);
system("pause");
}
链表操作
最新推荐文章于 2023-01-24 16:48:30 发布