From 975b9e5a59f025d6bbe2afab36e59343d439ae55 Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Sun, 31 May 2020 23:10:14 +0800 Subject: [PATCH] =?UTF-8?q?Create=20=E9=93=BE=E8=A1=A8=E7=9B=B8=E5=85=B3.m?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blogs/Algorithm/剑指 Offer/链表相关.md | 80 ++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 blogs/Algorithm/剑指 Offer/链表相关.md diff --git a/blogs/Algorithm/剑指 Offer/链表相关.md b/blogs/Algorithm/剑指 Offer/链表相关.md new file mode 100644 index 0000000..6c194dd --- /dev/null +++ b/blogs/Algorithm/剑指 Offer/链表相关.md @@ -0,0 +1,80 @@ +--- +链表相关 +--- + +[06: 从头到尾打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/) + +```java +class Solution { + public int[] reversePrint(ListNode head) { + ListNode temp = head; + int size = 0; + while (temp != null) { + temp = temp.next; + size++; + } + int[] result = new int[size]; + int index = size - 1; + while (head != null) { + result[index--] = head.val; + head = head.next; + } + return result; + } +} +``` + +```java +class Solution { + public int[] reversePrint(ListNode head) { + Stack stack = new Stack(); + ListNode temp = head; + while (temp != null) { + stack.push(temp); + temp = temp.next; + } + int size = stack.size(); + int[] print = new int[size]; + for (int i = 0; i < size; i++) { + print[i] = stack.pop().val; + } + return print; + } +} +``` + +[22:链表中倒数第 k 个节点](https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/) + +```java +class Solution { + public ListNode getKthFromEnd(ListNode head, int k) { + int length = 0; + ListNode temp = head; + while (temp != null) { + temp = temp.next; + length++; + } + for (int i = 0; i < length - k; i++) { + head = head.next; + } + return head; + } +} +``` + +```java +class Solution { + public ListNode getKthFromEnd(ListNode head, int k) { + ListNode h0 = head; + for (int i = 0; i < k; i++) { + h0 = h0.next; + } + while (h0 != null) { + h0 = h0.next; + head = head.next; + } + return head; + } +} +``` +