模板
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node
{
int id;
int score;
int num;
struct node *next;
} STU;
STU *pp=NULL;
STU *Creat();
void Print(STU *head);
void Find(STU *head, int num);
STU *Delete(STU *head, int num);
void Clear(STU *head);
STU *Insert(STU *head, int id, int score);
int main()
{
int num, id, score;
char s[10];
pp=Creat();//建立链表
while(~scanf("%s", s))
{
if(!strcmp(s,"print")) Print(pp);//输出(查找)链表
else if(!strcmp(s,"find"))
{
scanf("%d", &num);
Find(pp, num);//查询
}
else if(!strcmp(s,"delete"))
{
scanf("%d", &num);
pp=Delete(pp, num);//删除
}
else if(!strcmp(s,"insert"))
{
scanf("%d%d", &id, &score);
pp=Insert(pp, id, score);//插入
}
else if(!strcmp(s,"clear"))
{
Clear(pp);//清空
}
}
return 0;
}
STU *Creat()
{
STU *head=NULL, *p1, *p2;
p1=p2=(STU *)malloc(sizeof(STU));
scanf("%d%d", &p2->id, &p2->score);
while(p2->id!=0)
{
if(head==NULL) head=p1;
else p1->next=p2;
p1=p2;
p2=(STU *)malloc(sizeof(STU));
scanf("%d%d", &p2->id, &p2->score);
}
if(head!=NULL)p1->next=NULL;
return head;
}
void Print(STU *head)
{
STU *p;
for(p=head; p; p=p->next)
printf("Id:%d Score:%d\n", p->id, p->score);
}
void Find(STU *head, int num)
{
STU *p;
int isFind=1;
for(p=head; p; p=p->next)
{
if(p->id==num)
{
isFind=0;
printf("Score:%d\n", p->score);
break;
}
}
if(isFind)
printf("Not exist!\n");
}
STU *Delete(STU *head, int num)
{
STU *p, *q=NULL;
int isFind=1;
for(p=head; p; q=p, p=p->next)
{
if(p->id==num)
{
isFind=0;
if(!q) head=p->next;
else q->next=p->next;
free(p);
break;
}
}
if(isFind)
printf("Not exist!\n");
return head;
}
void Clear(STU *head)
{
STU *p, *q;
for(p=head; p; p=q)
{
q=p->next;
free(p);
}
}
STU *Insert(STU *head, int Id, int Score)
{
STU *p, *q=NULL, *New;
New=(STU *)malloc(sizeof(STU));
New->id=Id;
New->score=Score;
if(head==NULL)
{
head=New;
New->next=NULL;
}
else
{
for(p=head; p; q=p, p=p->next)
{
if(!q && New->id < p->id)
{
New->next=p;
head=New;
break;
}
else if(New->id < p->id && New->id > q->id)
{
New->next=p;
q->next=New;
break;
}
else if(New->id > p->id && !p->next)
{
New->next=NULL;
p->next=New;
break;
}
}
}
return head;
}
多次删除
struct link *delodd(struct link *head)
{
struct link *p=NULL, *q=NULL, *clear=NULL;
for(p=head; p; )
{
if(p->data%2)
{
clear=p;
if(!q)
{
head=p->next;
p=head;
}
else
{
q->next=p->next;
p=q->next;
}
free(clear);
}
else
{
q=p;
p=p->next;
}
}
return head;
}
逆序(反向)链表
struct Link* reverseLink(struct Link *Head)
{
struct Link *p1, *p2, *t=Head;
p2=Head->next;
t->next=NULL;
while(p2)
{
p1=p2;
p2=p2->next;
p1->next=t;
t=p1;
}
return t;
};