Interview ---- K elements at the bottom of the linked list

Source: Internet
Author: User

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;}
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.