每日一题之查找单链表的第K个节点

该博客探讨如何在一次遍历中同时实现单链表的逆置和查找第K个节点的方法,挑战高效算法设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

逆置/反转单链表+查找单链表的第K个节点,要求只能便利一次链表。

#include<stdio.h>
#include<malloc.h>

typedef int Datatype;
typedef struct node
{
	Datatype data;
	struct node *next;
}LinkedNode, *LinkList;

LinkList create_list()
{
	Datatype value[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int len = sizeof(value) / sizeof(Datatype);
	int i = 0;
	LinkedNode *list_head = NULL;
	LinkedNode *tmp = NULL;
	LinkedNode *p = NULL;

	list_head = (LinkedNode*)malloc(sizeof(LinkedNode));
	list_head->data = value[0];
	list_head->next = NULL;

	tmp = list_head;
	for (i = 1; i < len; i++)
	{
		while (tmp->next != NULL)
		{
			tmp=tmp->next;
		}
		p = (LinkedNode*)malloc(sizeof(LinkedNode));
		p->data = value[i];
		p->next = NULL;
		tmp->next = p;
	}
	return list_head;
}
void Print(LinkList list)
{
	LinkedNode *tmp = NULL;
	if (list == NULL)
	{
		return;
	}
	tmp = list;
	while (tmp != NULL)
	{
		printf("%d", tmp->data);
		tmp = tmp->next;
	}
	printf("\n");
	return;
}
void reverse_list(LinkList list)
{
	LinkedNode *pre = list;
	LinkedNode *cur = list->next;
	LinkedNode *next = NULL;

	if (list == NULL || list->next == NULL)
		return;

	/*在这里实现翻转*/
	while (cur != NULL)
	{
		next = cur->next;
		cur->next = pre;
		pre = cur;
		cur = next;
	}
	list->next = NULL;
	list = pre;
	Print(list);
	return;
}

void reverse_the_list(LinkedNode *cur, LinkList *list)
{
	LinkedNode *next = NULL;
	if (cur == NULL || cur->next == NULL)
	{
		*list = cur;
	}
	else
	{
		next = cur->next;
		reverse_the_list(next, list);
		next->next = cur;
		cur->next = NULL;
	}
	return;
}

int main()
{
	LinkList list = NULL;
	LinkedNode *temp = NULL;
	LinkList list2 = NULL;

	list = create_list();
	Print(list);
	reverse_list(list);

	list2 = create_list();
	temp = list2;
	reverse_the_list(temp, &list2);
	Print(list2);
	system("pasue");
	return 0;
}
运行结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值