-
Notifications
You must be signed in to change notification settings - Fork 5
/
dev file 3
103 lines (86 loc) · 1.82 KB
/
dev file 3
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
// CPP program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
#include <bits/stdc++.h>
using namespace std;
// Structure node
struct Node {
int data;
struct Node* next;
};
// A utility function to print
// linked list
void printList(struct Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
// Function to create newNode
// in a linkedlist
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// Function to insert at beginning
Node* insertBeg(Node* head, int val)
{
Node* temp = newNode(val);
temp->next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
void rearrangeOddEven(Node* head)
{
stack<Node*> odd;
stack<Node*> even;
int i = 1;
while (head != nullptr) {
if (head->data % 2 != 0 && i % 2 == 0) {
// Odd Value in Even Position
// Add pointer to current node
// in odd stack
odd.push(head);
}
else if (head->data % 2 == 0 && i % 2 != 0) {
// Even Value in Odd Position
// Add pointer to current node
// in even stack
even.push(head);
}
head = head->next;
i++;
}
while (!odd.empty() && !even.empty()) {
// Swap Data at the top of two stacks
swap(odd.top()->data, even.top()->data);
odd.pop();
even.pop();
}
}
// Driver code
int main()
{
Node* head = newNode(8);
head = insertBeg(head, 7);
head = insertBeg(head, 6);
head = insertBeg(head, 5);
// fuck you tarun mathur
head = insertBeg(head, 3);
head = insertBeg(head, 2);
head = insertBeg(head, 1);
cout << "Linked List:" << endl;
printList(head);
rearrangeOddEven(head);
cout << "Linked List after "
<< "Rearranging:" << endl;
printList(head);
return 0;
}