乐趣区

关于java:找出链表中倒数第k个元素

找出链表中倒数第 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 循环是让快指针先挪动到指定的节点,接着在第二个循环中再同时挪动快慢指针,当快指针挪动到最初一个时,那慢指针所对应的下一个节点即是须要找的节。

退出移动版