本篇目的:编程实现每次输入数据都插入到单链表的尾部。
一、原理
从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;
}