C语言使用尾插法建立一个单链表
#include<stdio.h>
typedef struct node{
int data;
struct node *next;
} Lnode;
Lnode *Tail_Insert(){
Lnode *LHead = NULL;
Lnode *LTemp = NULL;
Lnode *LTail = NULL;
LHead = (Lnode*)malloc(sizeof(Lnode));
LHead->next = NULL;
int x;
scanf("%d",&x);
while(x!=9999){
LTemp = (Lnode*)malloc(sizeof(Lnode));
LTemp->data = x;
LTemp->next = NULL;
if(LHead->next == NULL){
LHead ->next = LTemp;
}else{
LTail->next = LTemp;
}
LTail = LTemp;
scanf("%d",&x);
}
return LHead;
}
void printList(Lnode *L){
L = L->next;
while(L!= NULL){
printf("%d ",L->data);
L = L->next;
}
}
int main(){
Lnode *L = Tail_Insert();
printList(L);
return 0;
}
|