#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
struct Node {
int data;
Node* next;
Node* prev;
Node(int d)
{
data = d;
}
};
Node* insertEnd(Node* head, int data)
{
Node* node = new Node(data);
Node* last = head;
node->next = NULL; // link new node to NULL as it is last node
if (head == NULL) // if list is empty add in beginning.
{
head = node;
node->prev = NULL;
return head;
}
while (last->next != NULL) // Find the last node
last = last->next;
last->next = node; // Add the node after the last node of list
node->prev = last;
return head;
}
// This function prints contents of linked list starting from head
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << ' ';
node = node->next;
}
}
Node* rearrangeList(Node* head)
{
Node* newN = NULL;
Node* odd = head;
Node* even = head->next;
while (even != NULL) {
insertEnd(newN, even->data);
if (even->next == NULL) {
break;
}
even = even->next->next;
}
while (odd != NULL) {
insertEnd(newN, odd->data);
if (odd->next == NULL) {
break;
}
odd = odd->next->next;
}
return newN;
}
int main()
{
int t;
cin >> t;
while (t--) {
Node* head = NULL;
int n, m, x, y;
cin >> n;
while (n--) {
cin >> m;
head = insertEnd(head, m);
}
head = rearrangeList(head);
printList(head);
cout << endl;
}
return 0;
}
In this code we have to arrange the even position nodes in front and odd position nodes at end.
Whenever I try to run it I get a segmentation fault(on Code quotient) (on online gdb it gives no output).
Sample Input
1
7
1 -> 3 -> 5 -> 7 -> 9 -> 11 -> 13
Sample Output
3 7 11 1 5 9 13 Can anyone tell me where I am messing up in this problem .Thanks For the help!