//采用尾插法建立單鏈表,為些增加一個尾指針r,使其始終指向當(dāng)前鏈表的尾結(jié)點
include <stdio.h>
include <stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LinkList;
LinkList List_TailInsert(LinkList L)
{
int x; //設(shè)元素類型為整型
L = (LinkList)malloc(sizeof(LNode));
LNode *s, *r = L; //r為表尾指針
printf("請輸入表元素(以999結(jié)尾):");
scanf("%d", &x); //輸入結(jié)點的值
while (x != 999) //輸入999表示結(jié)束
{
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s; //r指向新的表尾結(jié)點
scanf("%d", &x);
}
r->next = NULL; //尾結(jié)點指針置空
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;
}
//運行結(jié)果:

WX20200715-150914.png