链表学习笔记(二)
一.先进先出
生成单链表
1.生成新节点 p=malloc(链表大小)
给新节点赋值 p->data ,p->next =NULL;
2.添加到表尾 tail->next = p;
3.设置新表尾 tail = p;
类C语言描述
struct node *creat1()
{
struct node *head,*tail,*p;
int e;
head = (struct node*)malloc(sizeof(LENG));
tail = head;
scanf("%d",&e);
while(e!=0)
{
p = (struct node*)malloc(sizeof(LENG));
p->data = e;
tail->next = p;
tail = p;
scanf("%d",&e);
}
tail->next = NULL;
return head;
}
二.先进后出
元素插入表头
生成链表
1.生成新节点 p=malloc(链表大小)
给新节点赋值 p->data ,p->next =NULL;
2.新节点指向原首节点
p->next=head->next;
3.新节点作为首元素
head->next = p ;
struct node *creat2()
{
struct node *head,*p;
int e;
head = (struct node*)malloc(sizeof(LENG));
head->next = NULL;
scanf("%d",&e);
while(e!=0)
{
p = (struct node*)malloc(sizeof(LENG));
p->data = e;
p->next = head->next;
head->next = p;
scanf("%d",&e);
}
return head;
}