-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlst.h
83 lines (79 loc) · 1.84 KB
/
linkedlst.h
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
#ifndef LINKED_LIST_PROBLEM
#define LINKED_LIST_PROBLEM
#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
class SinglyLinkedListNode {
public:
int data;
SinglyLinkedListNode *next;
SinglyLinkedListNode(int node_data) {
this->data = node_data;
this->next = nullptr;
}
};
class SinglyLinkedList {
public:
SinglyLinkedListNode *head;
SinglyLinkedListNode *tail;
SinglyLinkedList() {
this->head = nullptr;
this->tail = nullptr;
}
void insert_node(int node_data) {
SinglyLinkedListNode *node = new SinglyLinkedListNode(node_data);
if (!this->head)
this->head = node;
else
this->tail->next = node;
this->tail = node;
}
};
void print_singly_linked_list(SinglyLinkedListNode *node, string sep,
ofstream &fout) {
while (node) {
fout << node->data;
node = node->next;
if (node)
fout << sep;
}
}
SinglyLinkedListNode *reverse(SinglyLinkedListNode *llist) {
vector<int> temp;
SinglyLinkedList *ls = new SinglyLinkedList();
while (llist) {
temp.push_back(llist->data);
llist = llist->next;
}
auto rbegin = temp.rbegin();
auto rend = temp.rend();
while (rbegin != rend) {
ls->insert_node(*rbegin);
++rbegin;
}
}
SinglyLinkedListNode *mergeLists(SinglyLinkedListNode *head1,
SinglyLinkedListNode *head2) {
vector<int> temp;
while (head1) {
temp.push_back(head1->data);
head1 = head1->next;
}
while (head2) {
temp.push_back(head2->data);
head2 = head2->next;
}
std::sort(temp.begin(), temp.end());
SinglyLinkedList *it = new SinglyLinkedList();
auto begin = temp.begin();
auto end = temp.end();
while (begin != end) {
it->insert_node(*begin);
++begin;
}
return it->head;
}
#endif // !LINKED_LIST_PROBLEM