Although this question is simple, you must be careful. The bug-free capability is very important.
Analysis: if you do not know the length of the linked list, you can use the double pointer method to let a pointer go k steps first, and then the two pointers go at the same time,
When the previous pointer becomes NULL, the first pointer is the last k node ..
However, consider k <0, k> length and so on ..
Another typical example of double pointer is to find whether the two linked list intersection, see the http://blog.csdn.net/shoulinjun/article/details/20127223
// copyright @ L.J.SHOU Mar.05, 2014// find the last kth node in a list#include
#include
using namespace std;struct ListNode{ int val; ListNode *next; ListNode(int x):val(x), next(NULL){}};ListNode* LastKthNode(ListNode *list, int k){ assert(k >= 0); if(k == 0 || list == NULL) return NULL; ListNode *p(list); for(; k>0 && p; --k)p = p->next; if(k > 0) // list length less than k return NULL; while(p) { p = p->next;list = list->next; } return list;}int main(void){ ListNode *list(NULL), *node(NULL); list = new ListNode(1); list->next = new ListNode(2); list->next->next = new ListNode(3); node = LastKthNode(list, 30); if(node != NULL) cout << "node is : " << node->val << endl; while(list){ node = list->next;delete list;list = node; } return 0;}