1

I have been playing around with single linked lists in Rust. How do I implement a method which returns a mutable reference to the last element in the list in order to append an element?

I am aware of Learning Rust With Entirely Too Many Linked Lists and also pretty confident in using unsafe code, but is there really no safe implementation to append an element?

A non mutable reference is of course easy to implement (get_last_element()):

use std::mem;

#[derive(Debug)]
pub struct SingleLinkedList {
    head: Option<Box<Node>>,
}

#[derive(Debug)]
struct Node {
    data: u32,
    next: Option<Box<Node>>,
}

impl SingleLinkedList {
    fn new() -> Self {
        SingleLinkedList { head: None }
    }

    fn get_last_element(&self) -> Option<&Box<Node>> {
        match self.head {
            Some(ref el) => {
                let mut iterator = el;
                loop {
                    match iterator.next {
                        Some(ref next_el) => {
                            iterator = next_el;
                        }
                        None => return Some(iterator),
                    }
                }
            }
            None => return None,
        }
    }

    fn push_front(&mut self, _data: u32) {
        let new_head = Some(Box::new(Node {
            data: _data,
            next: mem::replace(&mut self.head, None),
        }));
        self.head = new_head;
    }
}

fn main() {
    let mut list = SingleLinkedList::new();
    list.push_front(1);
    list.push_front(2);

    let ptr = list.get_last_element();
    println!("PTR: {:?}", ptr);
    println!("{:?}", list);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Lukas E.
  • 99
  • 1
  • 6
  • 1
    I was able to modify this code to get a mutable reference without changing too much. What did you try? What issues did you run into? – Peter Hall Aug 28 '18 at 17:35
  • 3
    [The solution in the duplicate question applied to your code](https://play.rust-lang.org/?gist=c04fd844e19fcfed732fee6575b27ba9&version=stable&mode=debug&edition=2015). You can also fix it by switching to the Rust 2018 Edition preview, or by enabling `#![feature(nll)]` using a nightly Rust build. – Peter Hall Aug 28 '18 at 17:48
  • Thank you very much for your help - I was indeed only missing the move of the iterator in a seperate variable. – Lukas E. Aug 30 '18 at 06:51

0 Answers0