Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1876 from liyuxuan7762/patch-1
Browse files Browse the repository at this point in the history
更新使用栈实现反转链表
  • Loading branch information
youngyangyang04 authored Jan 31, 2023
2 parents 3d97894 + 51d11d8 commit 025c7f2
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions problems/0206.翻转链表.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"/>
Expand Down

0 comments on commit 025c7f2

Please sign in to comment.