Skip to content

Commit cbdef76

Browse files
authored
Update linked_list.md
1 parent 974969f commit cbdef76

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

data_structure/linked_list.md

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -86,20 +86,32 @@ public ListNode deleteDuplicates(ListNode head) {
8686
//如果不保存 前向,后向指针,那在头插法使用过程中,未免破坏原链条,需要new ListNode复制节点,内存开销大.不破坏原链条,是本题的难点
8787

8888
```java
89-
public ListNode reverseList(ListNode head) {
90-
ListNode pre = null, p = head;
91-
while (p != null) {
92-
// 保存当前head.Next节点,防止重新赋值后被覆盖
93-
// 一轮之后状态:nil<-1 2->3->4
94-
// prev p
95-
ListNode temp = p.next;
96-
p.next = pre;
97-
// pre 移动
98-
pre = p;
99-
// p 移动
100-
p = temp;
89+
/**
90+
* Definition for singly-linked list.
91+
* public class ListNode {
92+
* int val;
93+
* ListNode next;
94+
* ListNode() {}
95+
* ListNode(int val) { this.val = val; }
96+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
97+
* }
98+
*/
99+
class Solution {
100+
public ListNode reverseList(ListNode head) {
101+
ListNode res=new ListNode(-1);
102+
ListNode p=head;
103+
ListNode beh;
104+
while(p!=null){
105+
//保存p的后继节点
106+
beh=p.next;
107+
//把p头插入res
108+
p.next=res.next;
109+
res.next=p;
110+
//p置位
111+
p=beh;
112+
}
113+
return res.next;
101114
}
102-
return pre;
103115
}
104116
```
105117

0 commit comments

Comments
 (0)