mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
更新使用栈实现反转链表
更新使用栈实现反转链表
This commit is contained in:
@ -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`
|
||||

|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user