题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
ListNode(): m_nKey(0), m_pNext(nullptr){};
ListNode(int x): m_nKey(x), m_pNext(nullptr){};
};
int main(){
int n;
while(cin >> n){
ListNode *head = new ListNode(0);
ListNode *cur = head;
for(int i = 0; i < n; i++){
int t;
cin >> t;
ListNode *temp = new ListNode(t);
cur->m_pNext = temp;
cur = cur->m_pNext;
}
head = head->m_pNext;
int k;
cin >> k;
if(k > n || k == 0){
cout << 0 << endl;
continue;
}
ListNode *fast = head, *slow = head;
for(int i = 0; i < k; i++){
fast = fast->m_pNext;
}
while(fast != nullptr){
fast = fast->m_pNext;
slow = slow->m_pNext;
}
cout << slow->m_nKey << endl;;
}
return 0;
}