链表头插和尾插
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct list
{
int data;
struct list *next;
};
typedef struct list ST;
/*
ST *creat_link()//尾插
{
int a;
ST *h,*p,*q;
h = (ST *)malloc(sizeof(ST)*1); //头结点
p = h;
scanf("%d",&a);
while(a != 0)
{
q = (ST *)malloc(sizeof(ST)*1); //产生新节点
q->data = a;
p->next = q; // 将新节点连接到表尾
p = q; // 将 p 指向当前表尾
scanf("%d",&a);
}
p->next = NULL; //表尾置空
return h;
}
*/
ST *creat_link() //头插
{
int a;
ST *h,*q;
h = (ST *)malloc(sizeof(ST)*1); //头结点
h->next = NULL;
scanf("%d",&a);
while(a != 0)
{
q = (ST *)malloc(sizeof(ST)*1); //产生新节点
q->data = a;
q->next = h->next; //将新节点插到表头
h->next = q; // 将头节点的指针指向新节点
scanf("%d",&a);
}
return h;
}
int main()
{
ST *head,*q;
head = creat_link();
q = head->next;
while(q != NULL)
{
printf("%d ",q->data);
q = q->next;
}
return 0;
}
当输入 2 3 4 5 0时,头插结果为5 4 3 2,尾插的结果为 2 3 4 5