剑指offer:面试题15、链表中倒数第 K 个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

代码示例

//双指针,两个指针指向头结点,一个指针先走K步,然后两个指针一直向前移动
//直到先走的指针指向链表末尾,后走的指针指向的节点即为倒数第K个节点
public class Offer15 {
    public static void main(String[] args) {
        //构建链表
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        Offer15 testObj = new Offer15();
        ListNode res = testObj.findKthToTail(head, 2);
        System.out.println(res.val);
    }

    public ListNode findKthToTail(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode preP = head;
        while (preP != null && k-- > 0) {
            preP = preP.next;
        }

        if (k > 0)
            return null;
        ListNode postP = head;
        while (preP != null) {
            preP = preP.next;
            postP = postP.next;
        }
        return postP;
    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) {
            this.val = val;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/ITxiaolei/p/13166907.html