-
Notifications
You must be signed in to change notification settings - Fork 0
/
Node.cpp
106 lines (95 loc) · 1.68 KB
/
Node.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
#include "Node.h"
Node::Node(int _index, int _key)
{
state = UNLABELED;
parent = NULL;
children = NULL;
leftSibling = NULL;
rightSibling = NULL;
rank = 0;
state = UNLABELED;
index = _index;
key = _key;
}
Node::Node()
{
parent = NULL;
children = NULL;
leftSibling = NULL;
rightSibling = NULL;
rank = 0;
state = UNLABELED;
}
// add children to the root node.
bool Node::addChild(Node* node)
{
if (children != NULL)
{
children->addSibling(node);
}
else
{
children = node;
node->parent = this;
rank = 1;
}
return true;
}
// add sibling to the linked list.
bool Node::addSibling(Node* node)
{
Node* temp = rightMostSibling();
if (temp == NULL)
return false;
temp->rightSibling = node;
node->leftSibling = temp;
node->parent = this->parent;
node->rightSibling = NULL;
if (parent)
parent->rank++;
return true;
}
// remove node.
bool Node::remove()
{
if (parent)
{
parent->rank--;
if (leftSibling)
{
parent->children = leftSibling;
}
else if (rightSibling)
{
parent->children = rightSibling;
}
else
parent->children = NULL;
}
if (leftSibling)
leftSibling->rightSibling = rightSibling;
if (rightSibling)
rightSibling->leftSibling = leftSibling;
leftSibling = NULL;
rightSibling = NULL;
parent = NULL;
return true;
}
Node* Node::leftMostSibling()
{
if (this == NULL)
return NULL;
Node* temp = this;
while (temp->leftSibling)
temp = temp->leftSibling;
return temp;
}
Node* Node::rightMostSibling()
{
if (this == NULL)
return NULL;
Node* temp = this;
while (temp->rightSibling)
temp = temp->rightSibling;
return temp;
}