Prove safety offer: the list reciprocal k-th node (the double pointer)

topic:

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

answer:

Solution one:

First linked list into a ArrayList, and then get the K penultimate code is as follows:

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

    ListNode(int val) {
        this.val = val;
    }
}*/

import java.util.ArrayList;
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null){
            return null;
        }
        ArrayList<ListNode> list = new ArrayList<ListNode>();
        while(head!=null){
            list.add(head);
            head = head.next;
        }
        if(k<1||k>list.size()){
            return null;
        }
        return list.get(list.size()-k);

    }
}

Solution two:

Double pointer method, fast faster than slow k-th position is null when the fast, slow reaching the penultimate position k, as follows:

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null){
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        int i=0;
        while(i<k){
            if(fast==null){
                return null;
            }
            fast = fast.next;
            i++;
        }
        while(fast!=null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

 

Published 92 original articles · won praise 2 · Views 8415

Guess you like

Origin blog.csdn.net/wyplj2015/article/details/104859121