本篇目的:程式設計實作每次輸入資料都插入到單連結清單的尾部。
一、原理

從head開始,基于周遊算法,找到尾結點,用指針p指向它,将新結點temp連結到p的後面。
二、完整程式
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* CreateNode(int x)
{//為資料x生成一個結點
//成功後,傳回指向新結點的指針
//失敗後,傳回空指針
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
if(temp==0)return 0;//失敗
temp->data=x;//寫入資料
temp->next=0;//防止指針懸空
return temp;
}
struct node *find_tail(struct node*head)
{//主調函數要保證head不能為空連結清單
//傳回最後一個結點的位址
struct node *p=head;
while(p->next!=0)
{
p=p->next;
}
return p;
}
struct node *push_tail(struct node*head,int t)
{//head指向的是結第一個點
//傳回插入結點後的連結清單的第一個結點的位址
struct node *temp;
temp=CreateNode(t); //生成一個結點
if(head==NULL) //連結清單為空
return temp;
struct node *p=find_tail(head);
p->next=temp;
return head;
}
void print_link_list(struct node *head)
{/*//head指向的就是資料,不帶頭結點 **/
struct node *p=head;
while(p!=0)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main(void)
{
struct node *head=0;
head=push_tail(head,1);
print_link_list(head);
head=push_tail(head,2);
head=push_tail(head,5);
head=push_tail(head,8);
head=push_tail(head,11);
print_link_list(head);
return 0;
}