Everyone. I am Kartik. I am new to all the programming scene. So I am facing some silly issues.
So here is the problem.
I was supposed to the separate even and odd numbers in a linked list. more specifically to put all the even elements at last after odd elements.
#include <bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node *next;
node *prev;
node(int d) {
data = d;
next = NULL;
}
};
node *first = NULL;
node *second = NULL;
void create(int arr[], int n) {
node *t;
node *last;
first = new node(arr[0]);
last = first;
for (int i = 1; i < n; i++) {
node *t = new node(arr[i]);
last->next = t;
last = t;
}
}
void EvenafterOdd(node *&first, node *&second) {
node *temp = first;
node *temp1 = second;
node *t;
node *last;
while (temp) {
int x = temp->data;
if (second == NULL) {
second = new node(x);
last = second;
// second = last;
} else if (x % 2 == 0) {
node *t = new node(x);
last->next = t;
t = last;
} else if (x % 2 == 1) {
node *t = new node(x);
t->next = second;
second = t;
}
}
}
void Rprint(node *&head) {
node* temp = head;
if (temp == NULL) {
return;
}
cout << temp->data << " ";
Rprint(temp->next);
}
int main(int argc, char const *argv[])
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
create(arr, n);
Rprint(first);
cout<<endl;
EvenafterOdd(first, second);
Rprint(first);
cout<<endl;
Rprint(second);
return 0;
}
So for the input 1 2 2 2 1.
The expected output is 1 1 2 2 2.
But in my code. the problem is the program just gets stuck after printing the first list. and its actually supposed to print the second list in the proper expected out.
Thanks in advance for everone who helps.