求单链表倒数第K个节点

求单链表倒数第K个值

题目:

找出单链表的倒数第K个元素,比如给定单链表:1->2->3->4->5,则链表的倒数第2个元素为4


1、单链表中的每个节点包含数据和指向下一个节点的指针

public class LNode {
    int data; //数据域
    LNode next;  //下一个节点的引用
}


2、顺序遍历两遍就是,第一次遍历求出链表的整个长度n,第二次遍历求得第n-k+1个元素就是倒数第K个元素,该方法需要对链表进行两次遍历


3、快慢指针法,就是使用两个指针,一个快指针,一个慢指针,开始两个指针指向头节点,然后快指针移动K个位置,这时候两个指针之间的距离为K,然后两个指针同时移动,当快指针指向的节点为null的时候,慢指针所指的节点即为倒数第K个节点


4、代码实现

public class _015 {

    /**
     * 快慢指针法
     * @param head 链表的头节点
     * @param k
     * @return
     */
    public static LNode FindLastK(LNode head, int k) {
        if (head == null || head.next == null)
            return head;
        LNode slow, fast;
        slow = fast = head.next;
        int i;
        for (i = 0; i < k && fast != null; ++i) {
            fast = fast.next;
        }
        if (i < k)
            return null;
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

    //顺序遍历两遍法
    public static LNode findLastK1(LNode head, int k) {
        if (head == null || head.next == null)
            return head;
        LNode tmpLNode = head.next;
        int n = 0;
        while (head.next != null) {
            n++;
            head = head.next;
        }
        head.next = tmpLNode;
        int t = n - k + 1;
        while (head.next != null) {
            if (t == 0)
                return head;
            t--;
            head = head.next;
        }
        return null;
    }

    /**
     * 构造一个带有头节点的链表
     * head->1->2->3->4->5
     * @param args
     */
    public static void main(String[] args) {
        LNode head = new LNode();
        head.next = null;
        LNode tmp = null;
        LNode cur = head;

        for (int i = 1; i < 7; i++) {
            tmp = new LNode();
            tmp.data = i;
            tmp.next = null;
            cur.next = tmp;
            cur = tmp;
        }

        for (cur = head.next; cur != null; cur = cur.next) {
            System.out.print("构造的链表:"+cur.data + " ");
        }
        System.out.println();
        System.out.println("快慢指针求得的数值:"+FindLastK(head, 3).data);
        System.out.println("顺序遍历两遍求得的值:"+findLastK1(head, 3).data);
    }

}

猜你喜欢

转载自www.cnblogs.com/javatalk/p/11333737.html