单链表尾插入法

单链表尾插入法

看了网上很多人写的,懵懵懂懂,自己小白一个花了很长时间才搞明白,这里对很多需要注意的事项都标注了起来,适合0基础,希望大家共同进步




/*  */
#include <stdio.h>		// ptintf; scanf	
#include <stdlib.h>	// 分配内存,释放内存
#include <stdlib.h>

/* 方式1:链表结构体含数据域 */
// 指针域:指向下一个节点
// 节点:node
typedef struct listStruct{
	int data;
	struct listStruct *next;
}listnode,listhead;	


static listhead *init_head(listhead *head, listnode *end);
static listnode *insert_node(int data, listnode *end);


int main(int argc, char **argv)
{
	listhead *head;
	listnode *end;
	int data1 = 1;
	int data2 = 2;
	head = init_head(head, end);	// 注意,必须要将返回值赋给head才能完成初始化
	end = head;	// end指向了head指向的内存空间,end->next = head->next = NULL,注:该语句不能放在init_head()函数中

	end = insert_node(data1, end);	// 必须要将尾节点返回,否则尾节点不会更新
	end = insert_node(data2, end);

	// 从头节点开始遍历,当node->next指向0地址时表示到了链表尾
	while( head->next != NULL ){
		head = head->next;
		printf("%d \n\r",head->data);
	}
	
	return 0;
}


/* 返回类型为 listhead *    
   初始化链表头,头节点数据域不存放数据 */
static listhead *init_head(listhead *head, listnode *end)
{
	head = (listhead *)malloc( sizeof(head) );	// head是一个指针
	head->next = NULL;	// 指向0地址	
	return head;
}


/* 插入节点:尾插法 */
static listnode *insert_node(int data, listnode *end)
{
	listnode *node;
	node = (listnode *)malloc( sizeof(node) );
	node->data = data;
	end->next = node;	// 尾节点指针 指向新插入的节点
	end = node;		// 新插入的节点变成尾节点
	node->next = NULL;
	return end;
}





  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值