-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0143-ReorderList.cs
55 lines (50 loc) · 1.47 KB
/
0143-ReorderList.cs
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
//-----------------------------------------------------------------------------
// Runtime: 108ms
// Memory Usage: 30 MB
// Link: https://leetcode.com/submissions/detail/346867621/
//-----------------------------------------------------------------------------
namespace LeetCode
{
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class _0143_ReorderList
{
public void ReorderList(ListNode head)
{
if (head == null) return;
ListNode slow = head, fast = head;
while (fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
ListNode prev = null, curr = slow, temp;
while (curr != null)
{
temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
ListNode first = head, second = prev;
while (second.next != null)
{
temp = first.next;
first.next = second;
first = temp;
temp = second.next;
second.next = first;
second = temp;
}
}
}
}