`
u010815305
  • 浏览: 28612 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

链表中的倒数第k个节点

 
阅读更多
题目描述:

输入一个链表,输出该链表中倒数第k个结点。
(hint: 请务必使用链表。)

输入:

输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为两个整数n和k(0<=n<=1000, 0<=k<=1000):n代表将要输入的链表元素的个数,k代表要查询倒数第几个的元素。
输入的第二行包括n个数t(1<=t<=1000000):代表链表中的元素。

输出:

对应每个测试案例,
若有结果,输出相应的查找结果。否则,输出NULL。

样例输入:
5 2
1 2 3 4 5
1 0
5
样例输出:
4
NULL

#include<stdio.h>
#include<stdlib.h>
struct ListNode
{
	int    m_nValue;
	ListNode* m_pNext;
};
ListNode * findKthToTail(ListNode* pListHead,unsigned int k)
{
	if(pListHead==NULL||k==0)
		return NULL;
	ListNode* pAhead=pListHead;
	ListNode* pBehind=NULL;
	
	for(unsigned int i=0;i<k-1;i++)
	{
		if(pAhead->m_pNext!=NULL)
			pAhead=pAhead->m_pNext;
		else
		{
			return NULL;
		}
	}
	
	pBehind =pListHead;
	
	while(pAhead->m_pNext!=NULL)
	{
		pAhead=pAhead->m_pNext;
		pBehind=pBehind->m_pNext; 
	}
	
	return pBehind;
} 

int main()
{
	int number,k;
	
	while(scanf("%d %d",&number,&k)!=EOF)
	{
		int headData;
		scanf("%d",&headData);
		ListNode* pHead=(ListNode*)malloc(sizeof(ListNode));
		
		pHead->m_nValue=headData;
		pHead->m_pNext=NULL;
		
		ListNode* pCur=pHead;
		
		for(int i=0;i<number-1;i++)
		{
			int data;
			scanf("%d",&data);
			ListNode* pNode=(ListNode*)malloc(sizeof(ListNode));
			pNode->m_nValue=data;
			pNode->m_pNext=NULL;
			
			
			pCur->m_pNext=pNode;
			pCur=pCur->m_pNext; 
		} 
			ListNode* find = findKthToTail(pHead,k);
			printf("%d",find->m_nValue);
		
	}
}


结果:

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics