先搞个结点
typedef struct node
{
int data;
struct node *next;
} node;
建立链表
先看下头插法,头结点与新结点之间一直往头插就得事
//头插法
int main()
{
node *L,*p,*q;
int i;
L=(node*)malloc(sizeof(node));
L->next=NULL;
for(i=0;i<5;i++)
{
p=(node *)malloc(sizeof(node));
p->data=i;
p->next=L->next;
L->next=p;
}
q=L->next;
while(q!=NULL)
{
printf("%d ",q->data);
q=q->next;
}
return 0;
}
头插法也太叛逆了吧,咱顺着逻辑搞个尾插法试试
//尾插法
int main()
{
node *L,*p,*q,*r;
int i;
L=(node*)malloc(sizeof(node));
r=L;
L->next=r;
for(i=0;i<5;i++)
{
p=(node *)malloc(sizeof(node));
p->data=i;
L->next=p;
L=p;
}
L->next=NULL;
q=r->next;
while(q!=NULL)
{
printf("%d ",q->data);
q=q->next;
}
return 0;
}
宿舍熄灯了,不想写了,拜拜,下次见