@@ -13,45 +13,70 @@ impl<T: Ord> SkewHeap<T> {
13
13
self . root . is_none ( )
14
14
}
15
15
16
- pub fn push ( & mut self , x : T ) {
17
- self . root = Node :: merge ( self . root . take ( ) , Node :: singleton ( x ) ) ;
16
+ pub fn push ( & mut self , value : T ) {
17
+ self . root = Node :: merge ( self . root . take ( ) , Node :: singleton ( value ) ) ;
18
18
}
19
19
20
20
pub fn pop_min ( & mut self ) -> Option < T > {
21
21
let root = self . root . take ( ) ?;
22
- let x = root. x ;
22
+ let x = root. value ;
23
23
self . root = Node :: merge ( root. l , root. r ) ;
24
24
Some ( x)
25
25
}
26
26
}
27
27
28
28
pub struct Node < T : Ord > {
29
- x : T ,
29
+ value : T ,
30
30
l : Option < Box < Node < T > > > ,
31
31
r : Option < Box < Node < T > > > ,
32
32
}
33
33
34
34
impl < T : Ord > Node < T > {
35
- pub fn singleton ( x : T ) -> Option < Box < Node < T > > > {
35
+ pub fn singleton ( value : T ) -> Option < Box < Node < T > > > {
36
36
Some ( Box :: new ( Node {
37
- x ,
37
+ value ,
38
38
l : None ,
39
39
r : None ,
40
40
} ) )
41
41
}
42
42
43
+ /*
43
44
pub fn merge(a: Option<Box<Node<T>>>, b: Option<Box<Node<T>>>) -> Option<Box<Node<T>>> {
44
45
match (a, b) {
45
46
(None, b) => b,
46
47
(a, None) => a,
47
48
(Some(a), Some(b)) => {
48
- let ( mut a, b) = if a. x < b. x { ( a, b) } else { ( b, a) } ;
49
+ let (mut a, b) = if a.value < b.value { (a, b) } else { (b, a) };
49
50
a.r = Self::merge(a.r, Some(b));
50
51
swap(&mut a.l, &mut a.r);
51
52
Some(a)
52
53
}
53
54
}
54
55
}
56
+ */
57
+
58
+ pub fn merge ( mut a : Option < Box < Node < T > > > , mut b : Option < Box < Node < T > > > ) -> Option < Box < Node < T > > > {
59
+ let mut stack = Vec :: new ( ) ;
60
+ let mut ret = loop {
61
+ match ( a, b) {
62
+ ( None , b) => break b,
63
+ ( a, None ) => break a,
64
+ ( Some ( x) , Some ( y) ) => {
65
+ let ( mut x, y) = if x. value < y. value { ( x, y) } else { ( y, x) } ;
66
+ let r = x. r . take ( ) ;
67
+ stack. push ( x) ;
68
+ a = r;
69
+ b = Some ( y) ;
70
+ }
71
+ }
72
+ } ;
73
+ while let Some ( mut x) = stack. pop ( ) {
74
+ x. r = ret;
75
+ swap ( & mut x. l , & mut x. r ) ;
76
+ ret = Some ( x) ;
77
+ }
78
+ ret
79
+ }
55
80
}
56
81
57
82
#[ cfg( test) ]
@@ -61,7 +86,9 @@ mod tests {
61
86
#[ test]
62
87
fn test_skew_heap ( ) {
63
88
let mut heap = SkewHeap :: new ( ) ;
64
- for x in [ 1 , 1 , 2 , 2 , 3 , 3 , 3 , 3 , 4 , 4 , 5 , 5 , 5 , 6 , 6 , 7 , 8 , 8 , 9 , 9 , 9 ] {
89
+ for x in [
90
+ 1 , 1 , 2 , 2 , 3 , 3 , 3 , 3 , 4 , 4 , 5 , 5 , 5 , 6 , 6 , 7 , 8 , 8 , 9 , 9 , 9 ,
91
+ ] {
65
92
heap. push ( x) ;
66
93
}
67
94
let mut v = Vec :: new ( ) ;
@@ -72,6 +99,9 @@ mod tests {
72
99
} ;
73
100
v. push ( x) ;
74
101
}
75
- assert_eq ! ( v, vec![ 1 , 1 , 2 , 2 , 3 , 3 , 3 , 3 , 4 , 4 , 5 , 5 , 5 , 6 , 6 , 7 , 8 , 8 , 9 , 9 , 9 ] ) ;
102
+ assert_eq ! (
103
+ v,
104
+ vec![ 1 , 1 , 2 , 2 , 3 , 3 , 3 , 3 , 4 , 4 , 5 , 5 , 5 , 6 , 6 , 7 , 8 , 8 , 9 , 9 , 9 ]
105
+ ) ;
76
106
}
77
107
}
0 commit comments