Offer to prove safety of the programming problem (Java implementation) - the list penultimate k nodes

Title Description

Input a linked list, the linked list output reciprocal k-th node.

note:

The subject can not use the first list and then inverting the output of the k th node way as inverted list will change the node point next

A thought

Stack storage stack using reverse order of the k-th node pop

achieve

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.Stack;
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        // Stack
        Stack<ListNode> stack = new Stack<>();
        if(head == null) return null;
        int count = 0;
        while(head != null){
            stack.add(head);
            head = head.next;
            count++;
        }
        ListNode res = null;
        if(count < k) return res;
        for(; k > 0; k--){
            res = stack.pop();
        }
        return res;
    }
}

Ideas two

List set length N, find the first node nk is the k-th node

Providing two pointers P1 and P2, P1 let mobile nodes K, as well as the N - K nodes may move. At this time, let P1 and P2 move simultaneously, can know when the end of the list is moved to P1, P2 moved to the N - K nodes at the location K is the penultimate node.

achieve

public  class Solution {
     public ListNode FindKthToTail (ListNode head, int K) {
         // find the first node nk 
        IF (head == null ) return  null ; 
        ListNode RES = head;     // RES of the nk is 
        the while (head =! null K && -> 0 ) { 
            head = head.next; 
        } 
        IF (K> 0) return  null ;
         the while (head =! null ) { 
            RES = res.next;
            head = head.next;
        }
        return res;
    }
}

 Ideas Reference: https://www.nowcoder.com/discuss/198840

Guess you like

Origin www.cnblogs.com/MWCloud/p/11323067.html