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
版权声明:本文标题:rust - Insert function that inserts new node at the end of the linked list - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741588614a2386986.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论