题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <bits/stdc++.h>
using namespace std;
struct ListNode{
int m_nKey;
ListNode* m_pNext;
ListNode():m_nKey(0),m_pNext(NULL){}
ListNode(int x):m_nKey(x),m_pNext(NULL){}
};
int main(){
int n,k,val,i;
while(cin>>n){
ListNode* head=new ListNode();//带有头结点,注意头结点没有存储数字
ListNode* curr=head;
for(i=0;i<n;i++){//正向建立链表
cin>>val;
ListNode* temp=new ListNode(val);
head->m_pNext=temp;
head=head->m_pNext;
}
cin>>k;
ListNode *fast=curr,*slow=curr;//快慢指针
for(i=0;i<k;i++)//先让快指针移动k步
fast=fast->m_pNext;
while(fast!=NULL){//当快指针到达尾部时,此时慢指针指向的就是倒数第k个节点
slow=slow->m_pNext;
fast=fast->m_pNext;
}
cout<<slow->m_nKey<<"\n";;
}
return 0;
}