链表的基本操作(标题待定)
一struct node
{
int data;
struct node *next;
};
typedef struct node SLIST;
SLIST *creat_slist()
{
int c;
SLIST *head,*s,*r;
head=(SLIST *)malloc(sizeof(SLIST));
r=head;
scanf("%d",&c);
while(c!=-1)
{
s=(SLIST *)malloc(sizeof(SLIST));
s->data=c;
r->next=s;
r=s;
scanf("%d",&c);
}
r->next='\0';
return head;
}
void print_slist(SLIST *head)
{
SLIST *p;
p=head->next;
if(p=='\0')
printf("Linklist is null!\n");
else
{
printf("head");
do
{
printf("->%d",p->data);
p=p->next;
}while(p!='\0');
printf("End\n");
}
}
void insert_snode(SLIST *head,int x,int y)
{
SLIST *s,*p,*q;
s=(SLIST *)malloc(sizeof(SLIST));
s->data=y;
q=head;
p=head->next;
while((p!='\0')&&p->data!=x)
{
q=p;
p=p->next;
}
s->next=p;
q->next=s;
}
delete_snode(SLIST *head,int m)
{
SLIST *p,*q;
q=head;p=head->next;
while(p!='\0'&&p->data!=m)
{
q=p;p=p->next;
}
if(p->data==m)
q->next=p->next;
}
main()
{
SLIST *head;
int x,y,m;
clrscr();
scanf("%d%d",&x,&y);
scanf("%d",&m);
head=creat_slist();
print_slist(head); /*加入一個訪問函數*/
insert_snode(head,x,y);/*加入一個插入函數*/
print_slist(head);
delete_snode(head,m);/*加入一個刪除函數*/
print_slist(head);
}
二
#include <stdio.h>
struct student
{
long num; float score; struct student *next;
};int n;
struct student *creat()
{
struct student *head; struct student *p1,*p2;n=0;
p1=p2=( struct student*) malloc(sizeof(struct student));
scanf("%ld%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;/*重點在這里*/
p2=p1;
p1=(struct student*)malloc(sizeof(struct student));
scanf("%ld%f",&p1->num,&p1->score);
}
p2->next=NULL;/*重點在這里*/
return(head);
}
void print(struct student *head)
{
struct student *p;
printf("\nNow,These %d records are:\n",n); p=head;/*重點在這里*/
if(head!=NULL)
do
{
printf("%ld %5.1f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
struct student *del(struct student *head,long num)
{
struct student *p1,*p2;
if (head==NULL)
{
printf("\nlist null!\n");goto END;
}
p1=head;
while(num!=p1->num && p1->next!=NULL)
{
p2=p1;p1=p1->next;
}
if(num==p1->num)
{
if(p1==head)
head=p1->next;
else
p2->next=p1->next;
printf("delete:%ld\n",num);
n=n-1;
}
else
printf("%ld not been found!\n",num);
END:
return(head);
}
struct student *inser(struct student *head, struct student *stud)
{
struct student *p0,*p1,*p2;
p1=head;p0=stud;
if(head==NULL)
{
head=p0; p0->next=NULL;
}
else
{
while((p0->num>p1->num) && (p1->next!=NULL))
{
p2=p1; p1=p1->next;
}
if(p0->num<=p1->num)
{
if(head==p1)
head=p0;
else
p2->next=p0;
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
n=n+1;
return(head);
}
main()
{
struct student *head,stud;
long num;
clrscr();
scanf("%ld%f",&stud.num,&stud.score);
scanf("%ld",&num);
head=creat();
print(head);/*加入一個訪問函數*/
del(head,num);/*加入一個刪除函數*/
print(head);
inser(head,&stud);/*加入一個插入函數*/
print(head);
}