『自讨苦吃的写法』题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include<bits/stdc++.h> using namespace std; struct ListNode { int m_nKey; ListNode* m_pNext; ListNode(int val): m_nKey(val),m_pNext(nullptr){ }; }; //最简单的接口,但是不符合题意 //int solve(int n, int array[], int k ); ListNode * CreateList( int array[], int n ) { if( 0==n ) { return nullptr; } ListNode * head=new ListNode(array[0] ); ListNode * cur=head; for(int i=1; i<n; ++i) { ListNode * temp=new ListNode( array[i] ); cur->m_pNext=temp; cur=cur->m_pNext; } return head; } int solve( ListNode * head , int k) { ListNode * temp=head; int len=0; while( nullptr!=temp ) { ++len; temp=temp->m_pNext; } //cout<<"len="<<len<<endl; int loop; if( k>len ) { return -1;//表示不存在 } else { loop=len-k-1; } while( loop-- ) { head=head->m_pNext; } return head->m_pNext->m_nKey; } int main() { int n,k; while( ~scanf("%d",&n ) ) { int array[n]; for(int i=0; i<n; ++i) { scanf("%d",&array[i] ); } scanf("%d",&k); ListNode * head=CreateList( array , n); if( 0==k )//特判 { printf("0\n"); } else { printf("%d\n", solve(head,k) ); } } return 0; }