Last active
December 28, 2018 21:26
-
-
Save aknuds1/62a706b5baee7e345d2c11c7c73e9cd4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::cell::RefCell; | |
| use std::rc::Rc; | |
| pub struct SimpleLinkedList<T> { | |
| head: Option<Rc<RefCell<Element<T>>>>, | |
| } | |
| pub struct Element<T> { | |
| data: T, | |
| next: Option<Rc<RefCell<Element<T>>>>, | |
| } | |
| impl<T> SimpleLinkedList<T> { | |
| pub fn new() -> Self { | |
| SimpleLinkedList { head: None } | |
| } | |
| pub fn len(&self) -> usize { | |
| let mut ln = 0; | |
| let mut cur_option = self.head.as_ref().map(|x| x.clone()); | |
| while let Some(cur) = cur_option { | |
| ln += 1; | |
| cur_option = cur.borrow().next.as_ref().map(|x| x.clone()); | |
| } | |
| return ln; | |
| } | |
| pub fn push(&mut self, element: T) { | |
| let mut tail: Option<Rc<RefCell<Element<T>>>> = None; | |
| let mut cur_option = self.head.as_ref().map(|x| x.clone()); | |
| while let Some(cur) = cur_option { | |
| cur_option = cur.borrow().next.as_ref().map(|x| x.clone()); | |
| tail = Some(cur); | |
| } | |
| match tail.as_ref() { | |
| Some(e) => { | |
| e.borrow_mut().next = Some(Rc::new(RefCell::new(Element { | |
| data: element, | |
| next: None, | |
| }))); | |
| } | |
| None => { | |
| self.head = Some(Rc::new(RefCell::new(Element { | |
| data: element, | |
| next: None, | |
| }))); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment