【练习】输入一个单向链表,输出该链表中倒数第k 个结点

/************************************************************************/
/* 题目:输入一个单向链表,输出该链表中倒数第k 个结点。链表的倒数第0 个结点为链表的
尾指针。
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};         
解题思路参考http://www.diybl.com/course/3_program/c++/cppjs/20110510/555111.html*/
/************************************************************************/

#include <iostream>
using namespace std;

struct ListNode
{
	int m_nKey;
	ListNode* m_pNext;
};  

void Link(ListNode* &pHead,int n)
{
	if (pHead==NULL)
	{
		pHead=new ListNode;
		pHead->m_nKey=n;
		pHead->m_pNext=NULL;
	}
	else
	{
		ListNode* current=new ListNode;
		current->m_nKey=n;
		current->m_pNext=pHead;
		pHead=current;
	}
}

ListNode* Find_Kth_Element1(ListNode* pHead, int k)
{
	ListNode * pResult=pHead;
	int length=1;

	while (pHead->m_pNext!=NULL)
	{
		
		pHead=pHead->m_pNext;
		length++;
	}
	if (length<k)
	{
		return NULL;
	}
	for (int n=0;n<length-k;n++)
	{
		pResult=pResult->m_pNext;
	}
	return pResult;

}
ListNode* Find_Kth_Element2(ListNode* pHead, int k)
{
	ListNode * pResult=pHead;
	ListNode*pAhead=pHead;
	for (int i=0;i<k;i++)
	{
		if (pAhead!=NULL)
		{
			pAhead=pAhead->m_pNext;
		} 
		else
		{
			return NULL;
		}
		
	}

	while (pAhead!=NULL)
	{
		pAhead=pAhead->m_pNext;
		pResult=pResult->m_pNext;
	}
	return pResult;
}

int main()
{
	ListNode *pHead=NULL;
	Link(pHead,2);
	Link(pHead,3);
	Link(pHead,6);
	Link(pHead,4);
	Link(pHead,9);
	Link(pHead,7);
	//ListNode *result=Find_Kth_Element1(pHead,6);
	ListNode *result=Find_Kth_Element2(pHead,1);
	if (result)
	{
		cout<<result->m_nKey;
	}
	else
	{
		cout<<"error"<<endl;
	}
	

}

  

posted @ 2011-11-02 10:57  refazy  阅读(1025)  评论(0编辑  收藏  举报