Skip to content

Commit af1267f

Browse files
Add OddEvenListReordering class and method
Implement odd-even reordering for a singly linked list.
1 parent 0d71382 commit af1267f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class OddEvenListReordering{
12+
13+
public ListNode oddEvenList(ListNode head) {
14+
15+
if(head == null || head.next == null){
16+
return head;
17+
}
18+
19+
ListNode odd = head;
20+
ListNode even = head.next;
21+
ListNode evenHead = even;
22+
23+
while(even!= null && even.next!=null){ //only checking even cause even will hit the end before odd cause it's a step ahead always
24+
if(odd.next != null){
25+
odd.next = odd.next.next;
26+
odd = odd.next;
27+
}
28+
29+
if(even.next != null){
30+
even.next = even.next.next;
31+
even = even.next;
32+
}
33+
}
34+
35+
odd.next = evenHead;
36+
37+
return head;
38+
}
39+
}

0 commit comments

Comments
 (0)