[back]
Rust Safe Uni-Directional Link List
modified: 2015-04-16 22:42:34

    extern crate core;

    use std::rc::Rc;
    use std::fmt::Show;
    use core::cell::RefCell;

    struct LLI<T: Copy> {
        next:   RefCell<Option<Rc<LLI<T>>>>,
        item:   T
    }

    fn llnew<T: Copy>(i: T) -> LLI<T> {
        LLI {
            next: RefCell::new(Option::None),
            item: i
        }
    }

    fn lladd<T: Copy>(ci: Rc<LLI<T>>, i: T) {
        let ni: Rc<LLI<T>>;

        //let a: &Option<Rc<LLI<T>>> = *ci.next.borrow();

        match *(ci.next.borrow()) {
            None => {
                ni = Rc::new( LLI { next: RefCell::new(Option::None), item: i } );
            },
            Some(ref nxt) => {
                ni = Rc::new( LLI { next: RefCell::new(Option::Some(nxt.clone())), item: i} );
            }
        }
    
        *(ci.next.borrow_mut()) = Option::Some(ni);
    }

    fn display<T: Show + Copy>(mut _cur: Rc<LLI<T>>) {
        let mut nxt;
    
        let mut cur = _cur.clone();
    
        loop {
            println!("item:{} cur:{:p}", cur.item, &*cur);
            match *cur.next.borrow() {
                None => {
                    break;
                },
                Some(ref _nxt) => {
                    nxt = _nxt.clone();
                }
            }
            cur = nxt;
        }
    }

    fn llgetbyindex<T: Clone + Copy>(mut cur: Rc<LLI<T>>, ndx : uint) -> Option<Rc<LLI<T>>> {
        let mut nxt;
        let mut cndx: uint = 0;
    
        loop {
            if cndx == ndx {
                return Option::Some(cur.clone());
            }
            match *cur.next.borrow() {
                None => {
                    break;
                },
                Some(ref _nxt) => {
                    nxt = _nxt.clone();
                }
            }
            cur = nxt;
            cndx += 1;
        }
    
        Option::None
    }

    fn main() {
        //let mut root: LLI<uint> = llnew(1);
        let root: Rc<LLI<uint>> = Rc::new(llnew(1));
    
        lladd(root.clone(), 3);
        lladd(root.clone(), 2);
    
        match llgetbyindex(root.clone(), 1) {
            None => { },
            Some(p) => {
                lladd(p, 5);
            }
        }
    
        println!("hello");
        display(root.clone());
        println!("hello");
        display(root.clone());
        println!("done");
    }

This is my first linked list implementation. It worked but it was really not the most efficient implementation. I wrote another one using Box<T> instead of Rc<RefCell<T>> which you should be able to find, [index.py?tag=LINKED-LIST].