diff --git a/notes/6. 从尾到头打印链表.md b/notes/6. 从尾到头打印链表.md index 9e3f598b..50fb00d3 100644 --- a/notes/6. 从尾到头打印链表.md +++ b/notes/6. 从尾到头打印链表.md @@ -2,7 +2,7 @@ ## 题目链接 -[牛客网](https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) +[Leetcode](https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/) ## 题目描述 @@ -17,14 +17,22 @@ 要逆序打印链表 1-\>2-\>3(3,2,1),可以先逆序打印链表 2-\>3(3,2),最后再打印第一个节点 1。而链表 2-\>3 可以看成一个新的链表,要逆序打印该链表可以继续使用求解函数,也就是在求解函数中调用自己,这就是递归函数。 ```java -public ArrayList printListFromTailToHead(ListNode listNode) { - ArrayList ret = new ArrayList<>(); - if (listNode != null) { - ret.addAll(printListFromTailToHead(listNode.next)); - ret.add(listNode.val); - } +private ArrayList tmp = new ArrayList<>(); + +public int[] reverseBookList(ListNode head) { + recurse(head); + int[] ret = new int[tmp.size()]; + for (int i = 0; i < ret.length; i++) + ret[i] = tmp.get(i); return ret; } + +private void recurse(ListNode head) { + if (head == null) + return; + recurse(head.next); + tmp.add(head.val); +} ``` ### 2. 使用头插法 @@ -33,7 +41,7 @@ public ArrayList printListFromTailToHead(ListNode listNode) { 链表的操作需要维护后继关系,例如在某个节点 node1 之后插入一个节点 node2,我们可以通过修改后继关系来实现: -```java +```text node3 = node1.next; node2.next = node3; node1.next = node2; @@ -48,21 +56,23 @@ node1.next = node2;

```java -public ArrayList printListFromTailToHead(ListNode listNode) { +public int[] reverseBookList(ListNode head) { // 头插法构建逆序链表 - ListNode head = new ListNode(-1); - while (listNode != null) { - ListNode memo = listNode.next; - listNode.next = head.next; - head.next = listNode; - listNode = memo; - } - // 构建 ArrayList - ArrayList ret = new ArrayList<>(); - head = head.next; + ListNode dummy = new ListNode(-1); + int count = 0; while (head != null) { - ret.add(head.val); - head = head.next; + ListNode memo = head.next; + head.next = dummy.next; + dummy.next = head; + head = memo; + count++; + } + int[] ret = new int[count]; + ListNode cur = dummy.next; + int idx = 0; + while (cur != null) { + ret[idx++] = cur.val; + cur = cur.next; } return ret; } @@ -75,15 +85,16 @@ public ArrayList printListFromTailToHead(ListNode listNode) {

```java -public ArrayList printListFromTailToHead(ListNode listNode) { +public int[] reverseBookList(ListNode head) { Stack stack = new Stack<>(); - while (listNode != null) { - stack.add(listNode.val); - listNode = listNode.next; + while (head != null) { + stack.push(head.val); + head = head.next; } - ArrayList ret = new ArrayList<>(); + int[] ret = new int[stack.size()]; + int idx = 0; while (!stack.isEmpty()) - ret.add(stack.pop()); + ret[idx++] = stack.pop(); return ret; } ```