From 1904871bf67cde65f41bbb8bfcd1aca61e253534 Mon Sep 17 00:00:00 2001 From: JinhouLiu <5753889+JinhouLiu@users.noreply.github.com> Date: Sun, 28 Jul 2024 18:27:25 +0800 Subject: [PATCH] Create ListNodeProblem.java MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 链表相关 --- ListNodeProblem.java | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 ListNodeProblem.java diff --git a/ListNodeProblem.java b/ListNodeProblem.java new file mode 100644 index 0000000..d6eee3b --- /dev/null +++ b/ListNodeProblem.java @@ -0,0 +1,30 @@ + /** + * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 + * + * + * @param pHead ListNode类 + * @param k int整型 + * @return ListNode类 + */ + public ListNode FindKthToTail (ListNode pHead, int k) { + if (pHead == null||k==0) { + return null; + } + + Stack stack = new Stack<>(); + + ListNode current = pHead; + while (current != null) { + stack.add(current); + current = current.next; + } + if (stack.size() < k) { + return null; + } + int curIndex = 1; + while (stack.size() != 0 && curIndex < k) { + stack.pop(); + curIndex++; + } + return stack.pop(); + }