Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit8708d09

Browse files
author
applewjg
committed
Reorder List
Change-Id: I7d0abc3a6ac836a443ee7d0b280915f45625fce8
1 parentba66009 commit8708d09

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

‎ReorderList.java

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Jan 8, 2015
4+
Problem: Reorder List
5+
Difficulty: Easy
6+
Source: http://oj.leetcode.com/problems/reorder-list/
7+
Notes:
8+
Given a singly linked list L: L0->L1->...->Ln-1->Ln,
9+
reorder it to: L0->Ln->L1->Ln-1->L2->Ln-2->...
10+
You must do this in-place without altering the nodes' values.
11+
For example,
12+
Given {1,2,3,4}, reorder it to {1,4,2,3}.
13+
14+
Solution: Reverse the back half first, then reorder.
15+
*/
16+
17+
18+
/**
19+
* Definition for singly-linked list.
20+
* class ListNode {
21+
* int val;
22+
* ListNode next;
23+
* ListNode(int x) {
24+
* val = x;
25+
* next = null;
26+
* }
27+
* }
28+
*/
29+
publicclassSolution {
30+
publicvoidreorderList_1(ListNodehead) {
31+
ListNodeslow =head,fast =head;
32+
if (head ==null ||head.next ==null)return;
33+
while (fast.next !=null &&fast.next.next !=null) {
34+
fast =fast.next.next;
35+
slow =slow.next;
36+
}
37+
fast =slow.next;
38+
slow.next =null;
39+
slow =head;
40+
ListNodepre =null;
41+
while (fast !=null) {
42+
ListNodenext =fast.next;
43+
fast.next =pre;
44+
pre =fast;
45+
fast =next;
46+
}
47+
fast =pre;
48+
while (fast !=null) {
49+
ListNodefastnext =fast.next;
50+
fast.next =slow.next;
51+
slow.next =fast;
52+
fast =fastnext;
53+
slow =slow.next.next;
54+
}
55+
}
56+
publicvoidreorderList_2(ListNodehead) {
57+
ListNodeslow =head,fast =head;
58+
if (head ==null ||head.next ==null)return;
59+
while (fast.next !=null &&fast.next.next !=null) {
60+
fast =fast.next.next;
61+
slow =slow.next;
62+
}
63+
fast =slow.next;
64+
while (fast.next !=null) {
65+
ListNodemove =fast.next;
66+
fast.next =move.next;
67+
move.next =slow.next;
68+
slow.next =move;
69+
}
70+
fast =slow.next;
71+
slow.next =null;
72+
slow =head;
73+
while (fast !=null) {
74+
ListNodefastnext =fast.next;
75+
fast.next =slow.next;
76+
slow.next =fast;
77+
fast =fastnext;
78+
slow =slow.next.next;
79+
}
80+
}
81+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp