1. Title description
Input a linked list, and output the kth node from the bottom of the linked list. In order to conform to the habits of most people, this question starts counting from 1, that is, the end node of the linked list is the first node from the bottom.
For example, a linked list has 6 nodes. Starting from the head node, their values are 1, 2, 3, 4, 5, and 6. The third node from the bottom of this linked list is the node with the value 4.
Two, problem-solving ideas
Idea 1:
1. Count the length of the linked list and record it as n
2. Set a pointer to make it go (nk) step first, then you can find the Kth node
Idea two (dual pointer):
1. Set the dual pointer slow and fast so that they are both at the head.
2. Let fast go k steps first.
3. Let slow and fast go backward step by step at the same time, until fast is empty.
4. The position of slow is the penultimate position. K nodes
Three, code implementation
Realize one:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
if(head==null) return null;
ListNode cur=head;
int size=0;
while(cur!=null){
size++;
cur=cur.next;
}
cur=head;
while(size-k>0){
cur=cur.next;
size--;
}
return cur;
}
}
Implementation two:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
if(head==null) return null;
ListNode slow=head;
ListNode fast=head;
for(int i=0;i<k;i++){
fast=fast.next;
}
while(fast!=null){
slow=slow.next;
fast=fast.next;
}
return slow;
}
}