From 51d11d8e81b9217131d668ad940312614c898d46 Mon Sep 17 00:00:00 2001 From: Li Yuxuan <77979684+liyuxuan7762@users.noreply.github.com> Date: Mon, 23 Jan 2023 12:49:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BD=BF=E7=94=A8=E6=A0=88?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=8F=8D=E8=BD=AC=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新使用栈实现反转链表 --- problems/0206.翻转链表.md | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index 7db80fe1..4920b5b3 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -665,6 +665,42 @@ public class LinkNumbers } ``` + + +## 使用栈解决反转链表的问题 +* 首先将所有的结点入栈 +* 然后创建一个虚拟虚拟头结点,让cur指向虚拟头结点。然后开始循环出栈,每出来一个元素,就把它加入到以虚拟头结点为头结点的链表当中,最后返回即可。 + +```java +public ListNode reverseList(ListNode head) { + // 如果链表为空,则返回空 + if (head == null) return null; + // 如果链表中只有只有一个元素,则直接返回 + if (head.next == null) return head; + // 创建栈 每一个结点都入栈 + Stack stack = new Stack<>(); + ListNode cur = head; + while (cur != null) { + stack.push(cur); + cur = cur.next; + } + // 创建一个虚拟头结点 + ListNode pHead = new ListNode(0); + cur = pHead; + while (!stack.isEmpty()) { + ListNode node = stack.pop(); + cur.next = node; + cur = cur.next; + } + // 最后一个元素的next要赋值为空 + cur.next = null; + return pHead.next; +} +``` + +> 采用这种方法需要注意一点。就是当整个出栈循环结束以后,cur正好指向原来链表的第一个结点,而此时结点1中的next指向的是结点2,因此最后还需要`cur.next = null` +![image-20230117195418626](https://raw.githubusercontent.com/liyuxuan7762/MyImageOSS/master/md_images/image-20230117195418626.png) +