-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOddEvenLinkedList.java
More file actions
66 lines (48 loc) · 1.49 KB
/
Copy pathOddEvenLinkedList.java
File metadata and controls
66 lines (48 loc) · 1.49 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
package LeetcodePractice;
public class OddEvenLinkedList {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode odd = head;
ListNode even = head.next;
ListNode evenHead = even;
while (even != null && even.next != null) {
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}
public static ListNode createList(int[] values) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
for (int val : values) {
current.next = new ListNode(val);
current = current.next;
}
return dummy.next;
}
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val);
if (head.next != null) System.out.print(" -> ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
int[] input = {1, 2, 3, 4, 5};
ListNode head = createList(input);
System.out.print("Original List: ");
printList(head);
head = oddEvenList(head);
System.out.print("Reordered List: ");
printList(head);
}
}