4
NULL
第一种方法:(链表),使用两个指针,第一个指针直接遍历,使得与第二个指针的距离为k-1。那么按照这样再继续遍历。当二个指针指向链表尾部时,就是第倒数第k个结点。需要考虑k=0,和链表为空的情况。
/* ***********************************************
Author :bo-jwolf
Created Time :2015年02月11日 星期三 21:50:17
File Name :1517.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
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 = 1; 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()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n, k, temp;
while( scanf( "%d%d", &n, &k ) != EOF ){
ListNode *head = NULL;
ListNode *p = NULL;
p = new ListNode;
p ->m_pNext = NULL;
head = p;
for( int i = 1; i <= n; ++i ){
ListNode *q = NULL;
q = new ListNode;
scanf( "%d", &temp );
q -> m_nValue = temp;
q -> m_pNext = p -> m_pNext;
p -> m_pNext = q;
p = p ->m_pNext;
}
ListNode *t = FindKthToTail( head ->m_pNext, k );
if( t != NULL )
printf( "%d\n", t -> m_nValue );
else
puts("NULL");
}
return 0;
}
第二种方法,使用栈,根据栈的性质,先入后出,那么直接弹出k次,就可以得到相应值。需要注意的同上,其次就是当n<k。
/* ***********************************************
Author :bo-jwolf
Created Time :2015年02月11日 星期三 22:18:16
File Name :1517a.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include<stack>
using namespace std;
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
stack<int>Q;
int n, k, temp;
while( scanf( "%d%d", &n, &k ) != EOF ){
while( !Q.empty() ){
Q.pop();
}
for( int i = 1; i <= n; ++i ){
scanf( "%d", &temp );
Q.push( temp );
}
if( Q.empty() or k == 0 or n < k ){
puts("NULL");
}
else{
while( k-- ){
temp = Q.top();
Q.pop();
}
printf( "%d\n", temp );
}
}
return 0;
}