I have a linked list here with tests in it. It is a mutable singly linked list. I've modified it slightly and added a rank to the node. I want this linked list to be ordered putting the lower ranked item first. So, on the push() operation I simply want it to crawl the list and insert the node in the right spot.
This ALMOST works but when it attempts to push the third item, the iterator exits after the 2nd item.
Am I assigning the 2nd item improperly somehow?
// Push will insert according to rank - rank is ordered lowest first
pub fn push(&mut self, elem: T, rank: i32) {
if Option::is_none(&self.head) {
let new_node = Box::new(Node {
rank,
elem,
next: None,
});
self.head = Some(new_node); // First node written here
} else {
for ranked_node in self.head.iter_mut() {
if let Some(ref next) = ranked_node.next {
if next.rank >= rank {
// If the next is larger, add here
let new_node = Box::new(Node {
rank,
elem,
// New node points to next
next: Option::take(&mut ranked_node.next),
});
// set current node to our new noded
ranked_node.next = Some(new_node);
break;
}
// Else iterate to next ** after first loop, exists and never loops to the second one
} else {
// There is no higher next node, add at end
let new_node = Box::new(Node {
rank,
elem,
next: None,
});
ranked_node.next = Some(new_node); // second node written here
break;
}
}
}
}