数据结构和算法分析数据结构与算法

Leetcode-面试题 02.02 返回倒数第 k 个节点

2021-10-05  本文已影响0人  itbird01

面试题 02.02. 返回倒数第 k 个节点

解题思路

1.第一次遍历,得到大小,初始化一个数组
2.第二次遍历, 将值赋予数组
3.数组取size-k位置的值

解题遇到的问题

后续需要总结学习的知识点

是否可以一次遍历,得到结果?

##解法1
class Solution {
    public int kthToLast(ListNode head, int k) {
        int i = 0;
        ListNode t = head;
        while (t != null) {
            t = t.next;
            i++;
        }
        t = head;
        int[] temp = new int[i];
        i = 0;
        while (t != null) {
            temp[i++] = t.val;
            t = t.next;
        }
        return temp[i - k];
    }

    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读