用两个指针;初始化为头指针;用其中一个指针遍历链表,当该指针遍历到第k个节点时,另外一个指针开始从头节点开始遍历链表;两个指针之间的距离为k;遍历完链表时第二个指针所指向的节点就是倒数第K个:
#include<cstdio>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct node{
int val;
node *next;
node(){
next=NULL;
}
};
#define Fin freopen("/home/kapop/pro/1.txt","r",stdin);
#define Fout freopen("/home/kapop/pro/2.txt","w",stdout);
int main(){
/* Fin
Fout*/
int n;
int k,x;
while(cin>>n>>k){
node *head=NULL,*p=NULL,*T=NULL;
p=head=new node;
T=head;
int cnt=0;
for(int i=0;i < n; i++){
cin>>x;
p -> val=x;
p -> next=new node;
cnt++;
p=p->next;
if(k < cnt)
{
T=T->next;
}
}
cout<<"res: ";
cout<<T->val<<endl;}
return 0;
}
/*
10 3
1 2 3 4 5 6 7 8 9 10
11 5
1 2 3 4 5 6 7 8 9 10 11
12 5
1 2 3 4 5 6 7 8 9 10 11 12
res: 8
res: 7
res: 8
*/