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) +