Skip to content

Commit d88dd9e

Browse files
Create Day 16 Odd Even Linked List.cpp
1 parent 82fbf91 commit d88dd9e

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Day 16 Odd Even Linked List.cpp

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
PROBLEM:
2+
3+
4+
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the
5+
node number and not the value in the nodes.
6+
7+
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
8+
9+
Example 1:
10+
Input: 1->2->3->4->5->NULL
11+
Output: 1->3->5->2->4->NULL
12+
13+
Example 2:
14+
Input: 2->1->3->5->6->4->7->NULL
15+
Output: 2->3->6->7->1->5->4->NULL
16+
17+
Note:
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+
SOLUTION:
23+
24+
25+
/**
26+
* Definition for singly-linked list.
27+
* struct ListNode {
28+
* int val;
29+
* ListNode *next;
30+
* ListNode() : val(0), next(nullptr) {}
31+
* ListNode(int x) : val(x), next(nullptr) {}
32+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
33+
* };
34+
*/
35+
class Solution {
36+
public:
37+
ListNode* oddEvenList(ListNode* head) {
38+
39+
if(head==NULL)
40+
return NULL;
41+
42+
ListNode *result=head,*p1,*p2,*even,*p3;
43+
p1=head;
44+
p2=head->next;
45+
even=p2;
46+
47+
while(p1!=NULL && p2!=NULL)
48+
{
49+
p3=p2->next;
50+
if(p3==NULL)
51+
break;
52+
53+
p1->next=p1->next->next;
54+
p2->next=p2->next->next;
55+
56+
p1=p1->next;
57+
p2=p2->next;
58+
}
59+
60+
p1->next=even;
61+
62+
return result;
63+
64+
65+
}
66+
};

0 commit comments

Comments
 (0)