File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Given a singly linked list, group all odd nodes together followed by the even nodes.
3
+ * Please note here we are talking about the node number and not the value in the nodes.
4
+ *
5
+ * You should try to do it in place.
6
+ * The program should run in O(1) space complexity and O(nodes) time complexity.
7
+
8
+ Example 1:
9
+
10
+ Input: 1->2->3->4->5->NULL
11
+ Output: 1->3->5->2->4->NULL
12
+ Example 2:
13
+
14
+ Input: 2->1->3->5->6->4->7->NULL
15
+ Output: 2->3->6->7->1->5->4->NULL
16
+ Note:
17
+
18
+ The relative order inside both the even and odd groups should remain as it was in the input.
19
+ The first node is considered odd, the second node even and so on ...
20
+ */
21
+
22
+ /**
23
+ * Definition for singly-linked list.
24
+ * function ListNode(val) {
25
+ * this.val = val;
26
+ * this.next = null;
27
+ * }
28
+ */
29
+ /**
30
+ * @param {ListNode } head
31
+ * @return {ListNode }
32
+ */
33
+ const oddEvenLinkedList = head => {
34
+
35
+ if ( ! head ) {
36
+ return null ;
37
+ }
38
+
39
+ let odd = head ;
40
+ let even = head . next ;
41
+ let evenHead = even ;
42
+
43
+ while ( even !== null && even . next !== null ) {
44
+ odd . next = even . next ;
45
+ odd = odd . next ;
46
+ even . next = odd . next ;
47
+ even = even . next ;
48
+ }
49
+
50
+ odd . next = evenHead ;
51
+ return head ;
52
+ }
You can’t perform that action at this time.
0 commit comments