Skip to content

Commit 0224d94

Browse files
committed
add solution of problem 328: Odd Even Linked List
1 parent 66dcb3f commit 0224d94

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

OddEvenLinkedList328/README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
2+
3+
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
4+
5+
#####Example:
6+
Given `1->2->3->4->5->NULL`,
7+
8+
return `1->3->5->2->4->NULL`.
9+
10+
#####Note:
11+
The relative order inside both the even and odd groups should remain as it was in the input.
12+
13+
The first node is considered odd, the second node even and so on ...

OddEvenLinkedList328/Solution.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
public class Solution {
10+
public ListNode oddEvenList(ListNode head) {
11+
if (head == null)
12+
return null;
13+
14+
ListNode newHead = head;
15+
ListNode currOdd = head;
16+
ListNode currEven = head.next;
17+
ListNode evenHead = currEven;
18+
19+
while (currEven != null) {
20+
if (currOdd.next == null || currOdd.next.next == null)
21+
currOdd.next = evenHead;
22+
else
23+
currOdd.next = currOdd.next.next;
24+
25+
if (currEven.next != null)
26+
currEven.next = currEven.next.next;
27+
28+
currOdd = currOdd.next;
29+
currEven = currEven.next;
30+
}
31+
32+
if (currOdd != evenHead)
33+
currOdd.next = evenHead;
34+
35+
return newHead;
36+
}
37+
}

0 commit comments

Comments
 (0)