-
Notifications
You must be signed in to change notification settings - Fork 0
/
splay.c
87 lines (81 loc) · 2.27 KB
/
splay.c
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* splay.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cgleason <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/09/10 11:28:53 by cgleason #+# #+# */
/* Updated: 2018/09/10 12:13:44 by cgleason ### ########.fr */
/* */
/* ************************************************************************** */
#include "ants.h"
void rot_right(t_splay **root)
{
t_splay *pivot;
pivot = (*root)->left;
(*root)->left = pivot->right;
if ((*root)->left)
(*root)->left->parent = (*root);
pivot->right = (*root);
(*root)->parent = pivot;
pivot->pathparent = (*root)->pathparent;
pivot->parent = NULL;
(*root) = pivot;
}
void rot_left(t_splay **root)
{
t_splay *pivot;
pivot = (*root)->right;
(*root)->right = pivot->left;
if ((*root)->right)
(*root)->right->parent = (*root);
pivot->left = (*root);
(*root)->parent = pivot;
pivot->pathparent = (*root)->pathparent;
pivot->parent = NULL;
(*root) = pivot;
}
void splay(t_splay *root, int key)
{
if (!root || root->key == key)
return (splay);
if (root->key < key)
{
if (!root->left || root->left->key == key)
return (root);
if (root->left->key < key)
{
return (splay(root->left->left, key));
rot_right(&root);
}
else if (root->left->key > key)
{
return (splay(root->left->right, key));
rot_left(&root);
}
if (!root->left)
return (root);
else
return (rot_right(&root));
}
else
{
if (!root->right || root->left->key == key)
return (root);
if (root->right->key > key)
{
return (splay(root->right->right, key));
rot_left(&root);
}
else if (root->right->key < key)
{
return (splay(root->right->left, key));
rot_right(&root);
}
if (!root->right)
return (root);
else
return (rot_left(&root));
}
}