-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path143.java
More file actions
85 lines (84 loc) · 2.32 KB
/
143.java
File metadata and controls
85 lines (84 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
__________________________________________________________________________________________________
sample 1 ms submission
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
ListNode slow = head, fast = head, prev = null;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
if (fast != null) {
prev = slow;
slow = slow.next;
}
prev.next = null;
prev = null;
while (true) {
ListNode tmp = slow.next;
slow.next = prev;
prev = slow;
if (tmp != null) {
slow = tmp;
} else {
break;
}
}
ListNode cur = head, next = slow;
while (cur != null) {
ListNode tmp = cur.next;
cur.next = next;
cur = cur.next;
next = tmp;
}
}
}
__________________________________________________________________________________________________
sample 35544 kb submission
public class Solution {
public void reorderList(ListNode head)
{
if(head == null || head.next == null)
return;
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
ListNode newHead = slow.next;
slow.next = null;
ListNode pre = null;
ListNode cur = newHead;
while(cur != null)
{
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
ListNode head1 = head;
ListNode head2 = pre;
while(head1!= null && head2 != null)
{
ListNode head2Next = head2.next;
head2.next = head1.next;
head1.next = head2;
head1 = head2.next;
head2 = head2Next;
}
}
}
__________________________________________________________________________________________________