尾插法构建动态单向链表-不带头结点

本篇目的:编程实现每次输入数据都插入到单链表的尾部。

一、原理

从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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值