链表--如何查找单链表中倒数第k个元素

如何查找单链表中倒数第k个元素

思路:因为是单链表,只能从头至尾遍历。可以设置两个引用,其中一个引用比另外一个先前移k-1步,然后两个引用同时开始移动,当先前移的那个引用到达链表尾的时候,即指向为NULL时,另一个引用指向的位置就是所要查找的元素。

代码实现

public static Node findElem(Node head,int k) {
        if(k < 1) {
            System.out.println("k不合法");
            return null;
        }
        Node node1 = head;
        Node node2 = head;
        for(int i = 0;i < k-1 && node2 != null;i++) {
            node2 = node2.next;
        }
        if(node2 == null) {
            System.out.println("k不合法");
            return null;
        }
        while(node2.next != null) {
            node1 = node1.next;
            node2 = node2.next;
        }
        return node1;
    }

Node类:

class Node{
    int data;
    Node next = null;
    public Node(int data) {
        this.data = data;
    }

}

猜你喜欢

转载自blog.csdn.net/yangruxi/article/details/80329772