//头插法建立单链表
#include <stdio.h>
#include <malloc.h>
typedef struct LNode{
int data;
struct LNode *next;
}Node,*LinkList;
LinkList HeadInsert(LinkList &); //头插法建立单链表
void output(LinkList); //遍历输出
int main(void){
LinkList L;
HeadInsert(L);
output(L);
return 0;
}
//头插法建立单链表
LinkList HeadInsert(LinkList &L){
L = (Node *)malloc(sizeof(Node));
L->next = NULL;
int e;
scanf("%d",&e);
while(e != -1){ //输入-1表示结束输入
Node *s = (Node *)malloc(sizeof(Node));
s->data = e;
s->next = L->next;
L->next = s;
scanf("%d",&e);
}
return L;
}
//遍历输出
void output(LinkList L){
Node *p = L->next;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
}
//尾插法建立单链表
#include <stdio.h>
#include <malloc.h>
typedef struct LNode{
int data;
struct LNode *next;
}Node,*LinkList;
LinkList TailInsert(LinkList &); //尾插法建立单链表
void output(LinkList);
int main(void){
LinkList L;
TailInsert(L);
output(L);
return 0;
}
LinkList TailInsert(LinkList &L){ //尾插法建立单链表
L = (Node *)malloc(sizeof(Node));
Node *r = L;
int e;
scanf("%d",&e);
while(e != -1){ //输入-1表示结束输入
Node *s = (Node *)malloc(sizeof(Node));
s->data = e;
r->next = s;
r = s;
scanf("%d",&e);
}
r->next = NULL;
return L;
}
//遍历输出
void output(LinkList L){
Node *p = L->next;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
}