算法之链表获取倒数第K个值

问题描述

实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。
实例:

输入: 1->2->3->4->5 和 k = 2
输出: 4

方法一

class Solution {
    
    
    public int kthToLast(ListNode head, int k) {
    
    
        ListNode pre = head;
        List<Integer> values = new ArrayList();
        while(pre!=null){
    
    
            values.add(pre.val);
            pre = pre.next;
        }
        if(values.size() >= k){
    
    
            return values.get(values.size()-k);
        }
        return -1;
    }
}

方法二差值法

class Solution {
    
    
    public int kthToLast(ListNode head, int k) {
    
    
        //移动K步骤
        ListNode pre = head;
        ListNode post = head;
        //先将post移动K步骤
        int tmp = 0;
        while(k>tmp){
    
    
            post = post.next;
            tmp++;
        }
        while(post!=null){
    
    
            pre = pre.next;
            post = post.next;
        }
        if(pre!=null){
    
    
            return pre.val;
        }else{
    
    
            return -1;
        }

    }
}

猜你喜欢

转载自blog.csdn.net/dirksmaller/article/details/106916613
今日推荐