File tree Expand file tree Collapse file tree 1 file changed +60
-6
lines changed
Expand file tree Collapse file tree 1 file changed +60
-6
lines changed Original file line number Diff line number Diff line change 22 heap
33 This question requires you to implement a binary heap function
44*/
5- // I AM NOT DONE
65
76use std:: cmp:: Ord ;
87use std:: default:: Default ;
3736 }
3837
3938 pub fn add ( & mut self , value : T ) {
40- //TODO
39+ self . items . push ( value) ;
40+ self . count += 1 ;
41+
42+ let mut idx = self . count ;
43+ // 上浮操作
44+ while idx > 1 {
45+ let pidx = self . parent_idx ( idx) ;
46+ if ( self . comparator ) ( & self . items [ idx] , & self . items [ pidx] ) {
47+ self . items . swap ( idx, pidx) ;
48+ idx = pidx;
49+ } else {
50+ break ;
51+ }
52+ }
4153 }
4254
4355 fn parent_idx ( & self , idx : usize ) -> usize {
5769 }
5870
5971 fn smallest_child_idx ( & self , idx : usize ) -> usize {
60- //TODO
61- 0
72+ let lidx = self . left_child_idx ( idx) ;
73+ let ridx = self . right_child_idx ( idx) ;
74+
75+ // 如果没有左子节点,则返回0(表示没有子节点)
76+ if lidx > self . count {
77+ return 0 ;
78+ }
79+
80+ // 如果没有右子树
81+ if ridx > self . count {
82+ return lidx;
83+ }
84+
85+ if ( self . comparator ) ( & self . items [ lidx] , & self . items [ ridx] ) {
86+ lidx
87+ } else {
88+ ridx
89+ }
6290 }
6391}
6492
@@ -84,8 +112,34 @@ where
84112 type Item = T ;
85113
86114 fn next ( & mut self ) -> Option < T > {
87- //TODO
88- None
115+ if self . is_empty ( ) {
116+ return None ;
117+ }
118+
119+ let fvalue = self . items . swap_remove ( 1 ) ;
120+ self . count -= 1 ;
121+
122+ if self . count > 0 {
123+ let mut idx = 1 ;
124+
125+
126+
127+ while self . children_present ( idx) {
128+ let scidx = self . smallest_child_idx ( idx) ;
129+ if scidx == 0 {
130+ break ;
131+ }
132+
133+ if !( self . comparator ) ( & self . items [ idx] , & self . items [ scidx] ) {
134+ self . items . swap ( idx, scidx) ;
135+ idx = scidx;
136+ } else {
137+ break ;
138+ }
139+ }
140+ }
141+
142+ Some ( fvalue)
89143 }
90144}
91145
You can’t perform that action at this time.
0 commit comments