【data structure】之查找链表中倒数第N个元素

问题: 给定一个链表,在只遍历一遍的前提下查找倒数第n个元素。数据开销要求尽可能小。

思路:

设置两个哨兵指针,第一个指针先移动n个位置,然后第二个指针再从头结点与第一个指针一起移动。这样第一个指针跟第二个指针之间的距离为n个结点长度,因此当第一个指针移动到尾部的时候,第二个指针即指向倒数第n个结点。

代码:

#include <iostream>
using namespace std;

struct Node
{
	Node* next;
	int flag;
};

Node* reverse_find(Node* pt_head, int n)
{
	Node* pt_first_sentinel = pt_head;
	Node* pt_second_sentinel = pt_head;

	for (int i = 0; i < n; ++i)
	{
		pt_first_sentinel = pt_first_sentinel->next;
	}

	while (pt_first_sentinel != NULL)
	{
		pt_first_sentinel = pt_first_sentinel->next;
		pt_second_sentinel = pt_second_sentinel->next;
	}
	return pt_second_sentinel;
}

void link_list_test()
{
	Node* pt_head = new Node;
	Node* pt_node = pt_head;
	pt_head->flag = 1;
	for (int i = 2; i <= 8; ++i)
	{
		Node* pt_new_node = new Node;
		pt_new_node->flag = i;
		pt_node->next = pt_new_node;
		pt_node = pt_new_node;
	}
	pt_node->next = NULL;
	Node* result = reverse_find(pt_head, 8);
	cout << result->flag << endl;
}

int main()
{
	link_list_test();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值