Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use super::item::Item;
- use super::node::Node;
- use std::fmt::Display;
- use std::mem;
- use std::rc::Rc;
- pub fn insert_item<T>(start: &mut Node<T>, val: T, insert_before: fn(&T, &Item<T>) -> bool)
- where T: Display
- {
- println!("Creating item: {}", val);
- let mut current = mem::take(start);
- let mut previous = Node::empty();
- while let Some(x) = mem::take(&mut current.value) {
- match insert_before(&val, &x) {
- true => break,
- false => {
- if let Ok(mut a) = Rc::try_unwrap(x) {
- previous = current;
- current = mem::take(&mut a.next);
- }
- }
- }
- }
- let item = Node::new(Item::new(val, current));
- match previous.value {
- Some(x) => {
- if let Ok(mut a) = Rc::try_unwrap(x) {
- a.next = item
- }
- },
- None => *start = item,
- }
- }
- pub fn remove_item<T>(start: &mut Node<T>, val: T, value_equals: fn(&Item<T>, &T) -> bool)
- where T: Display
- {
- let mut current = start.clone();
- let mut previous = Node::empty();
- while let Some(x) = mem::take(&mut current.value) {
- match value_equals(&x, &val) {
- true => break,
- false => {
- if let Ok(mut a) = Rc::try_unwrap(x) {
- previous = current;
- current = mem::take(&mut a.next);
- }
- }
- }
- }
- match current.value {
- Some(x) => {
- if let Ok(mut a) = Rc::try_unwrap(x) {
- let next = mem::take(&mut a.next);
- match previous.value {
- Some(y) => {
- if let Ok(mut b) = Rc::try_unwrap(y) {
- b.next = next
- }
- },
- None => *start = next,
- }
- }
- }
- None => println!("Item {} does not exist!", val),
- }
- }
- pub fn remove_all<T>(start: &mut Node<T>)
- where T: Display
- {
- *start = Node::empty();
- }
- pub fn print_list<T>(start: &Node<T>)
- where T: Display
- {
- let mut current = start.clone();
- while let Some(x) = ¤t.value {
- current = x.print_get_next()
- }
- }
- pub fn print_iterator<T>(start: &Node<T>)
- where T: Display
- {
- struct ItemIterator<T> where T: Display {
- pub item: Node<T>
- }
- impl<T> Iterator for ItemIterator<T> where T: Display {
- type Item = Rc<Item<T>>;
- fn next(&mut self) -> Option<Rc<Item<T>>> {
- let mut current;
- current = match &self.item.value {
- Some(x) => x.next.clone(),
- None => Node::empty(),
- };
- mem::swap(&mut current, &mut self.item);
- current.value
- }
- }
- for item in (ItemIterator { item: start.clone() }) {
- item.print_get_next();
- }
- }
- pub fn print_array<T>(start: &Node<T>)
- where T: Display
- {
- if start.val_some() {
- let mut item = start.clone();
- let mut i = 0;
- while let Some(_) = &item.value {
- let elem = &start[i];
- item = match &elem.value {
- Some(x) => x.print_get_next(),
- None => Node::empty(),
- };
- i += 1
- }
- }
- }
- pub fn print_recursive<T>(start: &Node<T>)
- where T: Display
- {
- match &start.value {
- Some(x) => print_recursive(&x.print_get_next()),
- None => { },
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement