声明:
算法数据结构面试100题系列题目来自于:http://blog.csdn.net/v_JULY_v/article/details/6057286
//输出倒数第k个结点的值
#include <iostream>
using namespace std;
typedef struct tagNode
{
tagNode *pNext;
int data;
}Node;
/*
* 核心代码(输出倒数第n个元素)
*/
int LastN(Node *head, int num)
{
if (NULL == head)
{
return 1;
}
else
{
int n = LastN(head->pNext, num);
if (num == n)
{
cout<<"倒数第:"<<num<<"个数的值为:"<<head->data<<endl;
}
return n + 1;
}
}
//创建链表,并返回头结点
Node *Create()
{
Node *head = NULL;
Node *pTemp = NULL;
Node *pTail = NULL;
for (int i = 0; i < 10; ++i)
{
if (NULL == head)
{
head = new Node;
head->data = i;
head->pNext = NULL;
pTail = head;
}
else
{
pTemp = new Node;
pTemp->data = i;
pTemp->pNext = NULL;
pTail->pNext = pTemp;
pTail = pTemp;
}
}
return head;
}
//遍历链表
void Show(Node *head)
{
Node *pCur = head;
while (NULL != pCur)
{
cout<<pCur->data<<endl;
pCur = pCur->pNext;
}
}
int main()
{
Node *p = NULL;
p = Create();
Show(p);
LastN(p, 4);
return 0;
}