Skip to content

Commit d85780f

Browse files
committed
seperate even odd
1 parent 7891490 commit d85780f

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@
156156
- [Merge K sorted linked lists](https://practice.geeksforgeeks.org/problems/merge-k-sorted-linked-lists/1# "view question") - [Cpp Solution](./solutions/Merge%20K%20sorted%20linked%20lists.cpp)
157157
- [Multiply two linked lists](https://practice.geeksforgeeks.org/problems/multiply-two-linked-lists/1# "view question") - [Cpp Solution](./solutions/Multiply%20two%20linked%20lists.cpp)
158158
- [Delete nodes having greater value on right](https://practice.geeksforgeeks.org/problems/delete-nodes-having-greater-value-on-right/1# "view question") - [Cpp Solution](./solutions/Delete%20nodes%20having%20greater%20value%20on%20right.cpp)
159+
- [Segregate even and odd nodes in a Link List](https://practice.geeksforgeeks.org/problems/segregate-even-and-odd-nodes-in-a-linked-list5035/1 "view question") - [Cpp Solution](./solutions/Segregate%20even%20and%20odd%20nodes%20in%20a%20Link%20List.cpp)
159160
- []( "view question") - [Cpp Solution](./solutions/.cpp)
160161

161162
### Binary Tree
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
Segregate even and odd nodes in a Link List
3+
============================================
4+
5+
Given a link list of size N, modify the list such that all the even numbers appear before all the odd numbers in the modified list. The order of appearance of numbers within each segregation should be same as that in the original list.
6+
7+
Example 1:
8+
Input:
9+
N = 7
10+
Link List =
11+
17 -> 15 -> 8 -> 9 -> 2 -> 4 -> 6 -> NULL
12+
Output: 8 2 4 6 17 15 9
13+
Explaination: 17,15,8,9 are odd so they appear
14+
first and 2,4,6 are the even numbers that appear later.
15+
16+
Example 2:
17+
Input:
18+
N = 4
19+
Link List = 1 -> 3 -> 5 -> 7
20+
Output: 1 3 5 7
21+
Explaination: There is no even number.
22+
So ne need for modification.
23+
24+
Your Task:
25+
You do not need to read input or print anything. Your task is to complete the function divide() which takes N and head of Link List as input parameters and returns the head of modified link list.
26+
27+
Expected Time Complexity: O(N)
28+
Expected Auxiliary Space: O(N)
29+
30+
Constraints:
31+
1 ≤ N ≤ 100
32+
1 ≤ arr[i] ≤ 10000
33+
*/
34+
35+
Node *divide(int N, Node *head)
36+
{
37+
Node *dummy1 = new Node(-1);
38+
Node *dummy2 = new Node(-1);
39+
40+
auto t1 = dummy1, t2 = dummy2;
41+
auto t = head;
42+
43+
while (t)
44+
{
45+
if (t->data % 2 == 0)
46+
{
47+
t1->next = t;
48+
t = t->next;
49+
t1 = t1->next;
50+
t1->next = NULL;
51+
}
52+
else
53+
{
54+
t2->next = t;
55+
t = t->next;
56+
t2 = t2->next;
57+
t2->next = NULL;
58+
}
59+
}
60+
61+
t1->next = dummy2->next;
62+
return dummy1->next;
63+
}

0 commit comments

Comments
 (0)