Skip to content

Commit 96e30bf

Browse files
authored
Update linked_list.md
1 parent cbdef76 commit 96e30bf

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

data_structure/linked_list.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,60 @@ public void reorderList(ListNode head) {
262262
}
263263
```
264264

265+
我的解答(完整版!time:击败99.99% 空间:击败25.82%):
266+
```
267+
/**
268+
* Definition for singly-linked list.
269+
* public class ListNode {
270+
* int val;
271+
* ListNode next;
272+
* ListNode() {}
273+
* ListNode(int val) { this.val = val; }
274+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
275+
* }
276+
*/
277+
class Solution {
278+
public void reorderList(ListNode head) {
279+
ListNode fast=head;
280+
ListNode mid=head;
281+
while(fast!=null&&fast.next!=null){
282+
fast=fast.next.next;
283+
mid=mid.next;
284+
}
285+
ListNode head1=this.reverseList(mid.next);
286+
//很关键,没有这句话,就报:Found cycle in the ListNode
287+
mid.next=null;
288+
ListNode temp;
289+
ListNode temp1;
290+
ListNode p=head;
291+
while(head1!=null){
292+
temp=p.next;
293+
temp1=head1.next;
294+
295+
head1.next=p.next;
296+
p.next=head1;
297+
298+
p=temp;
299+
head1=temp1;
300+
}
301+
}
302+
public ListNode reverseList(ListNode head){
303+
ListNode res=new ListNode(-1);
304+
ListNode p=head;
305+
ListNode beh;
306+
while(p!=null){
307+
beh=p.next;
308+
p.next=res.next;
309+
res.next=p;
310+
311+
p=beh;
312+
}
313+
return res.next;
314+
}
315+
}
316+
317+
```
318+
265319

266320
#### 回文链表
267321

0 commit comments

Comments
 (0)