admin管理员组

文章数量:1293739

This is the code I have written following Learning Rust With Entirely Too Many Linked Lists. The tutorial doesn't implement an insert function, which I thought I should implement. I've been stuck since then.

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

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

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

    fn from(val: i32) -> LinkedList {
        LinkedList {
            head: Some(Node::new(val)),
        }
    }

    fn push(&mut self, val: i32) {
        let node = Box::new(Node {
            val,
            next: self.head.take(),
            // next: mem::replace(&mut self.head, None),
        });

        self.head = Some(node);
    }

    fn pop(&mut self) -> Option<i32> {
        match self.head.take() {
            None => None,
            Some(node) => {
                self.head = node.next;
                return Some(node.val);
            }
        }
    }

    fn insert(&mut self, val: i32) {
        let mut current = &mut self.head;
        while let Some(ref node) = current {
            current = &mut node.next;
        }
    }

    fn print(&self) {
        let mut current = self.head.as_ref();
        while let Some(node) = current {
            println!("{}", node.val);
            current = node.next.as_ref();
        }
    }
}

This is the insert function I had written:

fn insert(&mut self, val: i32) {
    // traverse till the end of the list
    let mut current = self.head.as_mut();
    while let Some(ref node) = current {
        current = node.next.as_mut();
    }
    // set the end (current) to  Some(New_Node)
    current = Some(&mut Node::New(val));
}

This code shows no error and compiles successfully:


#[test]
fn case_2() {
    let mut input = LinkedList::from(100);
    input.insert(101);
    input.insert(102);
    input.insert(103);
    input.insert(104);
    input.insert(105);
    input.print();
}

But when I print the linked list after insert a bunch of data only 100 is printed from when I initialized the linked list, which means the insert is not working. How can I solve this problem?

EDIT:

fn insert(&mut self, val: i32) {
        let new_node = Node::new(val);

        // traverse till the end of the list
        let mut current = &mut self.head;
        while let Some(node) = current {
            current = &mut node.next;
        }

        // set the end (current) to  Some(New_Node)
        *current = Some(new_node);
    }

insert function should be as above and it works properly.

WHY? I thought

&mut self.head == self.head.as_mut()

本文标签: rustInsert function that inserts new node at the end of the linked listStack Overflow