forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOddEvenList.java
More file actions
70 lines (57 loc) · 1.62 KB
/
OddEvenList.java
File metadata and controls
70 lines (57 loc) · 1.62 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
package com.leetcode.problems.medium;
import static com.util.LogUtil.newLine;
/**
* @author neeraj on 10/10/19
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class OddEvenList {
// Definition for singly-linked list.
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
private static void printList(ListNode head) {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.val + "\t");
temp = temp.next;
}
newLine();
}
public static void main(String[] args) {
ListNode sample = new ListNode(1);
sample.next = new ListNode(2);
sample.next.next = new ListNode(3);
sample.next.next.next = new ListNode(4);
sample.next.next.next.next = new ListNode(5);
printList(sample);
sample = oddEvenList(sample);
printList(sample);
}
public static ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return head;
}
ListNode slow = head;
ListNode prev = head.next;
ListNode fast = prev.next;
ListNode nextOfSlow;
while (fast != null) {
nextOfSlow = slow.next;
slow.next = fast;
prev.next = fast.next;
fast.next = nextOfSlow;
slow = slow.next;
prev = prev.next;
if (prev == null) {
break;
}
fast = prev.next;
}
return head;
}
}