Find the k-th node from the bottom of the singly linked list (c language)

Find the k-th node from the bottom of the single-item linked list (traverse only once)

To find the k-th node from the bottom of the one-way linked list, we can first traverse it to find the length of the linked list, and then set a pointer to go (nk) steps to find the k-th node from the bottom.


However, this requires two traversals, and if only one traversal is allowed we can use double pointers. Set a first pointer and a back pointer, both pointers point to the head node, the first pointer moves forward k steps first, then the two pointers move forward together, until the first pointer traverses the last node value is null, the last pointer It points to the penultimate kth node

code c language

typedef struct LNode{
  int data;
  struct LNode *next;
}

//带头节点   
int find (LNode * head, int k){
     LNode *p = head->next->next;
     LNode *pre = head->next;

     int i = 0;
     While(p){
         p=p->next;
         i++;
         if(i>k){
             pre = pre->next;
         }
     }
     if(pre == head)
         return -1;
     else
         return pre->data;
}


 

Guess you like

Origin blog.csdn.net/weixin_43537097/article/details/127808404