【C语言】链表的遍历、前插入和后插入

链表的遍历、前插入和后插入

概念:链表是一种数据结构,用于存储具有线性关系的数据元素。与数组不同,链表中的元素在内存中的位置不一定是连续的。链表中的每个元素称为节点,每个节点包含两个部分:数据域和指针域。指针域用于指向下一个节点,从而将各个节点连接起来形成链表。
图示
在这里插入图片描述
代码示例

#include<stdio.h>

struct Test
{
	int date;
	struct Test *node;

};

int printlink(struct Test *p)
{

	while(p!=NULL)
	{
		printf("%d ",p->date);
		p = p->node;	

	}
	putchar('\n');
}

int insertlink(struct Test *t, struct Test *new ,int data)
{
	while(t != NULL)
	{
		if(t->date == data)
		{
			new->node = t->node;
			t->node = new;
		}
		t = t->node;
	}

}
struct Test* insert_front(struct Test *head, struct Test *new, int data)
{
	if(head->date == data)
	{
		new->node = head;
		return new;
	}

	while(head != NULL)
	{
		if(head->node->date == data)
		{
			new->node = head->node;
			head->node = new;

		}
		head = head->node;
	}
}
void main()
{
	int arry[] = {1,2,3};
	struct Test *head = NULL;
	for(int i=0;i<(sizeof(arry)/sizeof(arry[0]));i++)
	{
		printf("%d\n",arry[i]);
	
	}
	struct Test t1 = {1,NULL};
	struct Test t2 = {2,NULL};
	struct Test t3 = {3,NULL};
	struct Test t4 = {4,NULL};
	struct Test t5 = {5,NULL};
	t1.node = &t2;
	t2.node = &t3;
	t3.node = &t4;
	t4.node = &t5;
	struct Test t = {33,NULL};
	struct Test tt = {33,NULL};
	printlink(&t1);
	head = insert_front(&t1, &t, 1);
	printlink(head);
	insertlink(head, &tt,1);
	printlink(head);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值