-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOddEvenLinkedList.java
More file actions
48 lines (39 loc) · 1.13 KB
/
OddEvenLinkedList.java
File metadata and controls
48 lines (39 loc) · 1.13 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
package leetcode;
import utils.ListNode;
import utils.Lists;
/**
* OddEvenLinkedList
* https://leetcode-cn.com/problems/odd-even-linked-list/
* 328. 奇偶链表
*
* @since 2020-11-13
*/
public class OddEvenLinkedList {
public static void main(String[] args) {
ListNode head = Lists.fromInts(new int[]{1, 2, 3, 4, 5}, -1);
OddEvenLinkedList sol = new OddEvenLinkedList();
sol.oddEvenList(head);
System.out.println();
}
public ListNode oddEvenList(ListNode head) {
if (head == null) {
return null;
}
ListNode oddEnd = head;
ListNode toMoveParent = head.next;
while (toMoveParent != null) {
if (toMoveParent.next == null) {
break;
}
ListNode oddEndNext = oddEnd.next;
ListNode toMove = toMoveParent.next;
ListNode toMoveNext = toMove.next;
oddEnd.next = toMove;
toMove.next = oddEndNext;
toMoveParent.next = toMoveNext;
oddEnd = oddEnd.next;
toMoveParent = toMoveParent.next;
}
return head;
}
}