//静态链表
#include <stdio.h>
struct student
{
int a;
int b;
struct student *next;
};
int main()
{
struct student st1,st2,*head,*p;
st1.a=1;
st1.b=2;
st2.a=3;
st2.b=4;
st1.next=&st2;
st2.next=NULL;
head=&st1;
p=head;
do
{
printf("%d %d\n",p->a,p->b);
p=p->next;
}while(p!=NULL);
return 0;
}
//动态链表
#include <stdio.h>
#include <stdlib.h>
struct student
{
float num,score;
struct student *next;
};
int n;
struct student *cre(void)//输入函数
{
struct student *p1,*p2,*head;
p1=p2=(struct student*)malloc(sizeof(struct student));
head=NULL;
scanf("%f%f",&p1->num,&p1->score);
while(p1->num!=0)
{
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p1=(struct student *)malloc(sizeof (struct student));
scanf("%f%f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
void print(struct student *head)//输出函数
{
do
{
printf("%.2f%.2f",head->num,head->score);
head=head->next;
}
while(head!=NULL);
}
int main()
{
struct student *p;
p=cre();
print(p);
return 0;
}
测试一个链表是不是空的
#include <stdio.h>
#include <stdlib.h>
struct student
{
float a,b;
struct student *next;
};
int isempty (struct student *p)
{
return p->next==NULL;
}
int main()
{
int i;
struct student *head;
head=(struct student*)malloc(sizeof(struct student));
i=isempty(head);
printf("%d",i);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct student
{
float a;
int b;
int c;
struct student *next;
};
int islast (struct student *p)//测试当前位置是否是链表末尾的函数
{
return p->next==NULL;
}
int main()
{
int n=0;
int l;
struct student *head,*p1,*p2;
head=p1=p2=(struct student*)malloc(sizeof(struct student));
while(n!=3)
{
scanf("%f%d%d",&p1->a,&p1->b,&p1->c);
n++;
if(n!=3)
{
p1=(struct student *)malloc(sizeof(struct student));
p2->next=p1;
p2=p1;
}
else
{
p1->next=NULL;
}
}
l=islast(p2);
printf("%d",l);
return 0;
}*/
#include <stdio.h>
#include <stdlib.h>
struct student
{
int a;
struct student *next;
};
struct student*find(int x,struct student *p)//寻找一个数字在链表的位置,仅仅是地址的位置
{
struct student *pt;
pt=p->next;
while(pt!=NULL&&pt->a!=x)
{
pt=pt->next;
}
return pt;
}
struct student*findprevious(int x,struct student *l)//寻找删除的上一个
{
while((l->next!=NULL&&l->next->a!=x))
{
l=l->next;
}
return l;
}
void delete(int x,struct student *l)//删除
{
struct student *p,*tmpcell;
p=findprevious(x,l);
tmpcell=p->next;
p->next=tmpcell->next;//p->next=p->next->next;
free(tmpcell);
}
void insert(int x,struct student *p)//插入
{
struct student *tmpcell;
tmpcell=(struct student*)malloc(sizeof(struct student));
tmpcell->a=x;
tmpcell->next=p->next;
p->next=tmpcell;
}
int main()
{
struct student *head,*p1,*p2;
int i=0;
head=p1=p2=(struct student *)malloc(sizeof(struct student));
while(i!=3)
{
scanf("%d",&p1->a);
i++;
if(i!=3)
{
p1=(struct student*)malloc(sizeof(struct student));
p2->next=p1;
p2=p1;
}
else
{
p2->next=NULL;
}
}
if(head->a==1)//如果删除的是第一个从第二个开始输出
{
head=head->next;
while(head!=NULL)
{
printf("%d",head->a);
head=head->next;
}
}
else
{
delete(1,head);
while(head!=NULL)
{
printf("%d",head->a);
head=head->next;
}
}
return 0;
}