-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStack.cpp
126 lines (112 loc) · 2.04 KB
/
Stack.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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include "Stack.h"
#define NULL 0
myList::myList() {
head = NULL;
n = 0;
}
myList::~myList() {
myNode *p;
while (head != NULL) {
p = head;
head = head->next;
delete p;
}
}
void myList::push(hNode* p) {
myNode* _new = new myNode();
_new->data = p;
*p->inNeighbours = true;
n++;
if (head == NULL) {
head = _new;
}
else {
myNode* temp = head;
head = _new;
_new->next = temp;
}
}
void myList::deqeue() {
if (head == NULL)
return;
myNode* temp = head;
*temp->data->inNeighbours = false;
head = head->next;
delete temp;
n--;
}
hNode* myList::top() {
if (head == NULL)
return NULL;
return head->data;
}
void myList::MergeSort(myNode*& headRef)
{
myNode* head = headRef;
myNode* a;
myNode* b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
{
return;
}
/* Split head into 'a' and 'b' sublists */
FrontBackSplit(head, a, b);
/* Recursively sort the sublists */
MergeSort(a);
MergeSort(b);
/* answer = merge the two sorted lists together */
headRef = SortedMerge(a, b);
}
myNode* myList::SortedMerge(myNode*& a, myNode*& b)
{
myNode* result = NULL;
/* Base cases */
if (a == NULL)
return(b);
else if (b == NULL)
return(a);
/* Pick either a or b, and recur */
if (*a->data->nodeWeight > *b->data->nodeWeight)
{
result = a;
result->next = SortedMerge(a->next, b);
}
else
{
result = b;
result->next = SortedMerge(a, b->next);
}
return result;
}
void myList::FrontBackSplit(myNode*& source, myNode*& frontRef, myNode*& backRef)
{
myNode* fast = NULL;
myNode* slow = NULL;
if (source == NULL || source->next == NULL)
{
/* length < 2 cases */
frontRef = source;
backRef = NULL;
}
else
{
slow = source;
fast = source->next;
/* Advance 'fast' two nodes, and advance 'slow' one node */
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
}
/* 'slow' is before the midpoint in the list, so split it in two
at that point. */
frontRef = source;
backRef = slow->next;
slow->next = NULL;
}