题解 | #获取链表倒数第K个元素#


import java.util.Stack;
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode FindKthToTail1(ListNode pHead, int k) {
        if (pHead == null || k == 0) return null;
    
        ListNode fast = pHead, slow = pHead;
        for (int i = 0; i < k; ++i) {
            if (fast == null) {
                return null;
            }
            fast = fast.next;
        }
        
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        
        return slow;
    }
/** ========================================================================================================== */
    
    /**
     * @Description
     * 时间复杂度O(n)
     * 空间复杂度O(n)
     *
     * @Author fucheng
     * @Date 2022-4-19 11:06
     * @Param [pHead, k]
     * @return cn.gfc.platform.leetcode.linked_list.model.ListNode
     */
    public ListNode FindKthToTail2(ListNode pHead, int k) {
        if (pHead == null || k == 0) return null;
    
        Stack<ListNode> stack = new Stack<>();
        
        while (pHead != null) {
            stack.push(pHead);
            pHead = pHead.next;
        }
    
        ListNode head = stack.pop();
        ListNode next = null;
        for (int i = 1; i < k; ++i) {
            if (stack.isEmpty()) return null;
            next = stack.pop();
            next.next = head;
            head = next;
        }
        
        return head;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务