forked from TARANG0503/DSA-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evenafterodd.cpp
151 lines (142 loc) · 2.58 KB
/
evenafterodd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *next;
node(int data)
{
this->data = data;
this->next = NULL;
}
};
node *head;
int length(node *head)
{
int count = 0;
node *ptr = head;
while (ptr != NULL)
{
ptr = ptr->next;
count++;
}
return count;
}
void push(int data)
{
// create a new linked list node from the heap
node *newnode = (node *)malloc(1 * sizeof(node));
newnode->data = data;
newnode->next = NULL;
if (head == NULL)
{
head = newnode;
return;
}
node *p2 = head;
while (p2->next != NULL)
{
p2 = p2->next;
}
p2->next = newnode;
}
node *evenAfterOdd(node *head)
{
node *even = new node(0);
node *etail = even;
node *odd = new node(0);
node *otail = odd;
while (head)
{
if (head->data % 2 == 0)
{
etail->next = head;
etail = head;
head = head->next;
etail->next = NULL;
}
else
{
otail->next = head;
otail = head;
head = head->next;
otail->next = NULL;
}
}
otail->next = even->next;
return odd->next;
}
// second method
node *evenafterodd(node *head)
{
node *evenhead = NULL, *eventail = NULL, *oddhead = NULL, *oddtail = NULL;
if (head == NULL)
{
return head;
}
while (head != NULL)
{
if (head->data % 2 == 0)
{
if (evenhead == NULL)
{
evenhead = head;
eventail = head;
}
else
{
eventail->next = head;
eventail = eventail->next;
}
}
else
{
if (oddhead == NULL)
{
oddhead = head;
oddtail = head;
}
else
{
oddtail->next = head;
oddtail = oddtail->next;
}
}
head = head->next;
}
if (oddhead == NULL)
{
return evenhead;
}
else
{
oddtail->next = evenhead;
}
if (evenhead != NULL)
{
eventail->next = NULL;
}
return oddhead;
}
void display(node *head)
{
node *p2 = head;
while (p2 != NULL)
{
cout << "->" << p2->data;
p2 = p2->next;
}
}
int main()
{
int n, data;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> data;
push(data);
}
evenAfterOdd(head);
display(head);
}