C语言 链表创建及操作

C语言 链表创建及操作

  • 第一部分构建链表,定义结构体,分别用头插法、尾插法实现,这里封装了打印函数:printf();做练习方便后续使用;对链表进行查找,并将查找到的值构建一个新的链表;链表的转置;具体代码如下:
#include<stdio.h>
#include<stdlib.h>
struct node  //定义结构体
{
	int data;    
	struct node *next;
};
void print_data(struct node *inc)	//封装函数做打印用
{
	printf("data = %d\n",inc->data);
}
void traverse(struct node *inc, void(*print)(struct node *))	//遍历链表并打印
{
	while(inc)
	{
		print(inc);
		inc = inc->next;
	}
}
void insertHead(struct node **inc, int n)		//头插法
{
	struct node *tmp = malloc(sizeof(struct node));
	tmp->data = n;
	tmp->next = *inc;
	*inc = tmp;
}
void insertTail(struct node **inc, int n)	//尾插法
{
	struct node *tmp = malloc(sizeof(struct node));
	tmp->data = n;
	tmp->next = NULL;
	while(*inc)
	{
		inc = &(*inc)->next;
	}
	*inc = tmp;
}
struct node *findNode(struct node **inc, int goal)	 	//链表查找,并把查找到的值,存入新的链表中
{
	struct node *newlist = NULL;  //新的链表
	struct node *tmp = *inc;  //中间节点接收传入的值
	struct node *pre;  //上一个节点
	struct node *cur;  //当前节点
	while(tmp->next)
	{
		if(goal == tmp->next->data)
		{
			pre = tmp;
			cur = tmp->next;
			tmp->next = cur->next;
			cur->next = newlist;
			newlist = cur;
		}else if(goal == tmp->data){
			*inc = (*inc)->next;
			tmp->next = newlist;
			newlist = tmp;
			tmp = *inc;
		}else{
			tmp = tmp->next;
		}
	}
	return newlist;
}
void transNode(struct node **inc)
{
	struct node *cur = *inc;
	struct node *pre = NULL;
	struct ndoe *tmp;
	while(*inc)
	{
		tmp = cur->next;
		cur->next = pre;
		pre = cur;
		cur = tmp;
	}
	*inc = pre;
}
int main()
{
	struct node *p = NULL;
	insertHead(&p,10);
    insertHead(&p,20);
    insertHead(&p,10);
    insertHead(&p,30);
    insertHead(&p,10);
    insertHead(&p,40);
	printf("_____create list_____\n");
	traverse(p,print_data);
	printf("_____old list_____\n");
	struct node *ret = findNode(&p, 10);
	traverse(p,print_data);
	printf("_____new list_____\n");
	traverse(ret,print_data);
	return 0;
}
  • 执行结果如下:
    在这里插入图片描述
  • 5
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值