-
Notifications
You must be signed in to change notification settings - Fork 6
/
OddEvenLinkedList.java
57 lines (45 loc) · 1.51 KB
/
OddEvenLinkedList.java
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
package com.shivaprasad.january.day17;
//Note: For Linked List problems, Just focus on method code because creating Linked List for every problem is a hectic task,
//and we don't need to worry about it.
//Problem Link: https://leetcode.com/problems/odd-even-linked-list/
public class OddEvenLinkedList {
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode dummyEvenNode = new ListNode(1000001);
ListNode dummyOddNode = new ListNode(1000001);
ListNode odd = dummyOddNode;
ListNode even = dummyEvenNode;
boolean oddPos = true;
ListNode currNode = head;
while(currNode!=null)
{
if(oddPos)
{
ListNode newNode = new ListNode(currNode.val);
odd.next = newNode;
odd = odd.next;
oddPos = false;
}
else
{
ListNode newNode = new ListNode(currNode.val);
even.next = newNode;
even = even.next;
oddPos = true;
}
currNode = currNode.next;
}
odd.next = dummyEvenNode.next;
return dummyOddNode.next;
//T.C: O(n)
//S.C: O(1)
}
}