#include<stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
//头插法建立单链表(节点次序和输入数据的顺序不一致)
LinkList List_HeadInsert(LinkList &L){
LNode *s;int x;
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}
//尾插法建立单链表(节点次序和输入数据的顺序一致)
LinkList List_TailInsert(LinkList &L){
int x;
L=(LNode*)malloc(sizeof(LNode));
LNode *s,*r=L;
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return L;
}
//打印单链表
void PrintList(LinkList L){
LNode *p=L->next;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main(){
LinkList T,W;
List_HeadInsert(T);
PrintList(T);
List_TailInsert(W);
PrintList(W);
}
运行结果:
1 2 3 4 5 6 7 8 9 9999
9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 9999
1 2 3 4 5 6 7 8 9