1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RustでunsafeもRefCellも用いずにリンクリストの末尾に要素を追加する

Posted at
#[derive(Debug)]
struct List<T> {
    root: Option<Box<Node<T>>>,
}
#[derive(Debug)]
struct Node<T> {
    value: T,
    next: Option<Box<Node<T>>>,
}
impl<T> List<T> {
    fn push_back(&mut self, value: T) {
        let mut node : &mut Option<Box<Node<T>>> = &mut self.root;
        let mut s = Vec::new();
        
        s.push(node);
        
        while s[0].is_some() {
	        if let Some(ref mut b) = s.pop().unwrap() {
		       	s.push(&mut b.next);
	    	}
	    }
        
        let mut node = s.pop().unwrap();
        
        *node = Some(Box::new(Node {
            value: value,
            next: None,
        }));
    }
}
fn main() {
	let mut l = List {
		root:Some(Box::new(Node {
			value: 1,
			next: None
		}))
	};
	
	l.push_back(2);
	
	println!("{:?}",l);
}

要素を一旦Vecに突っ込んでループの先頭でpopで取り出し、次の要素をVecにpushすることで実装できた。

1
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?