//采用尾插法建立单链表,为些增加一个尾指针r,使其始终指向当前链表的尾结点
include <stdio.h>
include <stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LinkList;
LinkList List_TailInsert(LinkList L)
{
int x; //设元素类型为整型
L = (LinkList)malloc(sizeof(LNode));
LNode *s, *r = L; //r为表尾指针
printf("请输入表元素(以999结尾):");
scanf("%d", &x); //输入结点的值
while (x != 999) //输入999表示结束
{
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s; //r指向新的表尾结点
scanf("%d", &x);
}
r->next = NULL; //尾结点指针置空
return L;
}
int main()
{
LinkList L, A;
A = (LinkList)malloc(sizeof(LNode));
A = List_TailInsert(L);
printf("尾插法建立的单链表:");
while (A->next != NULL)
{
A = A->next;
printf("%d ", A->data);
}
printf("\n");
return 0;
}
//运行结果: