输出单链表的倒数第K个节点

本文介绍了一种高效查找单链表中倒数第K个节点的方法,通过双指针技巧避免了计算链表长度的过程。该方法不仅提高了算法效率,还提供了具体的C++实现代码。

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

求解单链表第K个节点或者倒数第K个节点总是一个O(n)的问题!一般的求解倒数第K个问题是转换为求解第N-K个节点的问题,这样需要求出链表总长N,实际上可以做的更好!

求解倒数第K个节点更好的一种做法是不求解链表长度,使用一个指针指向第K个节点,另一个指针指向第一个节点,两个指针同步移动,当第一个指针移动到末尾,第二个指针就指向倒数第K个节点!

#include <iostream>
using namespace std;

struct list {
	int value;
	struct list *next;
};

struct list *insert(struct list *head, int v)
{
	if (head) {
		head->next = insert(head->next, v);
	} else {
		head = new struct list;
		head->value = v;
		head->next = 0;
	}
	return head;
}

struct list *getrnode(struct list *head, size_t k)
{
	struct list *cursor = head;
	while (cursor && k--)
		cursor = cursor->next;
	while (cursor) {
		head = head->next;
		cursor = cursor->next;
	}
	return head;
}

int main()
{
	struct list *head1 = 0;
	head1 = insert(head1, 0);
	head1 = insert(head1, 1);
	head1 = insert(head1, 2);
	head1 = insert(head1, 3);
	head1 = insert(head1, 4);
	head1 = insert(head1, 5);
	head1 = insert(head1, 6);
	head1 = insert(head1, 7);
	head1 = insert(head1, 8);
	head1 = insert(head1, 9);
	cout << "node: " << getrnode(head1, 3)->value << endl;
	cout << "node: " << getrnode(head1, 7)->value << endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值