和我一起迎接明天的太阳吧

klaus08

焦虑源于行动的匮乏

JZ14 链表中倒数最后k个结点

原题链接

描述

输入一个链表,输出一个链表,该输出链表包含原链表中从倒数第k个结点至尾节点的全部节点。

如果该链表长度小于k,请返回一个长度为 0 的链表。


示例1

输入:{1,2,3,4,5},1
返回值:{5}

##思路

  1. 遍历链表变量,存在数组中,然后按序创建链表。
  2. 假设链表长度为n,求k个结点组成的链表,只要返回第(n - k + 1) 个结点后面的不动就好了。
  3. 双指针,创建两个结点初始化都指向链表头结点,然后让第一个向后移 k 个结点,如果移动过程中指向null,说明该链表长度小于 k 直接返回null。第一个结点指向第k个时,两个新创建的结点再一起向后移动,直到先移动的结点为null,此时返回第二个结点。

解答

解答一

public class Solution {

    public static ListNode FindKthToTail (ListNode pHead, int k) {

        ArrayList<Integer> arrayList = new ArrayList<>();

        ListNode cur = pHead;
        ListNode res = new ListNode(-1);
        ListNode head = res;

        while (cur != null ){
            arrayList.add(cur.val);
            cur = cur.next;
        }

        if (k > arrayList.size())
            return null;
        else {
            // s = 5 - 3
            int s = arrayList.size() - k;
            while (s < arrayList.size()){
                res.next = new ListNode(arrayList.get(s));
                res = res.next;
                s++;
            }
        }

        return head.next;
    }
}

解答二

public class Solution {
    
    public static ListNode FindKthToTail (ListNode pHead, int k) {

        ListNode cur = pHead; //用于遍历链表统计长度
        ListNode res = new ListNode(-1);//用于指向倒数第k个结点
        int len = 0;

        while (cur != null ){
            len++;
            cur = cur.next;
        }
        if (k <= 0 || k> len) return null;

        int index = len -k + 1;

        while (index-- > 0){
            res.next = pHead;
            pHead = pHead.next;
        }
        return res.next;
    }
}

解答三

public class Solution {

    public static ListNode FindKthToTail(ListNode pHead, int k) {
        if (pHead == null)
            return null;
        ListNode start = pHead, end = pHead;

        while (k-- > 0) {
            if (start == null )
                return null;
            start = start.next;
        }

        while (start!= null){
            start = start.next;
            end = end.next;
        }

        return end;
    }
}
posted @ 2021-07-18 15:32  klaus08  阅读(31)  评论(0)    收藏  举报