Skip to content

Commit 26d5a40

Browse files
author
zj
committed
328. Odd Even Linked List
1 parent cb11913 commit 26d5a40

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# 328. Odd Even Linked List
2+
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.
3+
4+
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
5+
6+
##### Example:
7+
8+
Given `1->2->3->4->5->NULL`,
9+
10+
return `1->3->5->2->4->NULL`.
11+
12+
##### Note:
13+
14+
The relative order inside both the even and odd groups should remain as it was in the input.
15+
16+
The first node is considered odd, the second node even and so on ...
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {ListNode}
11+
*/
12+
//Distribution 18.75%,runtime 162ms
13+
var oddEvenList = function(head) {
14+
if(!head) return head;
15+
var ohead = head.next;
16+
var j = head;
17+
var o = head.next;
18+
var node = head.next;
19+
while(node && node.next){
20+
j.next = node.next;
21+
o.next = node.next.next;
22+
j = j.next;
23+
o = o.next;
24+
node = j.next;
25+
}
26+
j.next = ohead;
27+
return head;
28+
};

0 commit comments

Comments
 (0)