`
java-mans
  • 浏览: 11413364 次
文章分类
社区版块
存档分类
最新评论

【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;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics