-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day-256.cpp
67 lines (67 loc) · 1.56 KB
/
Day-256.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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class node{
public:
int value;
node*next;
};
node* getlist(int value) {
node* head = nullptr, *tail = nullptr;
for (int i=1; i<=value; ++i) {
if (head == nullptr) {
head= new node();
head->value = i;
tail = head;
}else {
tail->next = new node();
tail = tail->next;
tail->value = i;
}
}
return head;
}
class solution {
vector<int>values;
void extractvalues(node*head) {
node *temp = head;
while(head != nullptr) {
values.push_back(head->value);
head = head->next;
}
sort(values.begin(), values.end());
head = temp;
}
void setlist(node*head) {
node*temp = head;
int i=0;
while(temp != nullptr) {
temp->value = values.at(i++);
temp = temp->next;
}
}
public:
node* rearrange(node* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
extractvalues(head);
for (int i=1; i+1 < (int)values.size(); i+=2) {
swap(values.at(i) , values.at(i+1));
}
setlist(head);
return head;
}
};
int main(void){
node*n1 = getlist(5);
solution s1;
s1.rearrange(n1);
while (n1!=nullptr) {
cout << n1->value << ' ' ;
n1 = n1->next;
}
cout << '\n';
return 0;
}