更新使用栈实现反转链表

更新使用栈实现反转链表
This commit is contained in:
Li Yuxuan
2023-01-23 12:49:42 +08:00
committed by GitHub
parent 2ffbb82aa8
commit 51d11d8e81

View File

@ -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<ListNode> 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)
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>