找出链表中倒数第k个元素
实现:

public class GetKthFromEnd {
    public ListNode getKthFromEnd(ListNode head,int k){
        ListNode node = head;
        while(node != null && k > 0){
            node = node.getNext();
            k--;
        }
        ListNode listNode = head;
        while (node.getNext() != null){
            node = node.getNext();
            listNode = listNode.getNext();
        }
        return listNode.getNext();
    }
    public static void main(String[] args) {
        GetKthFromEnd.ListNode head = new GetKthFromEnd.ListNode(1);
        GetKthFromEnd.ListNode node1 = new GetKthFromEnd.ListNode(2);
        GetKthFromEnd.ListNode node2 = new GetKthFromEnd.ListNode(3);
        GetKthFromEnd.ListNode node3 = new GetKthFromEnd.ListNode(4);
        GetKthFromEnd.ListNode node4 = new GetKthFromEnd.ListNode(5);
        head.setNext(node1);
        node1.setNext(node2);
        node2.setNext(node3);
        node3.setNext(node4);
        GetKthFromEnd getKthFromEnd = new GetKthFromEnd();
        ListNode kthFromEnd = getKthFromEnd.getKthFromEnd(head, 2);//获取倒数第二个节点
 System.out.println(kthFromEnd.getValue());
    }
    static class ListNode{
        int value;
        ListNode next;
        public int getValue() {
            return value;
        }
        public void setValue(int value) {
            this.value = value;
        }
        public ListNode getNext() {
            return next;
        }
        public void setNext(ListNode next) {
            this.next = next;
        }
        ListNode(int x){
            this.value = x;
        }
    }
}

k假设为2,即找出倒数第2个节点(也就是要找到节点值为'4'的节点)
这里使用了快慢指针的办法,
方法getKthFromEnd中第一个while循环是让快指针先移动到指定的节点,接着在第二个循环中再同时移动快慢指针,当快指针移动到最后一个时,那慢指针所对应的下一个节点即是需要找的节。


步履不停
38 声望13 粉丝

好走的都是下坡路