萌新考研学C:单链表的头插和尾插实例测试
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
LinkList HeadInsert(LinkList &L){
LNode *s;
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d",&x);
while(x != 99){
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d",&x);
}
return L;
}
LinkList TailInsert(LinkList &L){
int x;
L = (LinkList)malloc(sizeof(LNode));
LNode *s, *r = L;
scanf("%d",&x);
while(x != 99){
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d",&x);
}
r->next = NULL;
return L;
}
void display(LinkList L){
LNode * p = L->next;
int len = 1;
while(p != NULL){
printf("第%d个元素是:%d\n", len, p->data);
p = p->next;
++len;
}
}
int main(){
LinkList L;
HeadInsert(L);
display(L);
TailInsert(L);
display(L);
return 0;
}
|