rustHow to iterate linked list in Rust
Iterating a linked list in Rust is done using a loop and the .next()
method. The loop will continue until the .next()
method returns None
.
let mut current = list.head;
while let Some(node) = current {
println!("{}", node.data);
current = node.next;
}
Code explanation
let mut current = list.head
: Declares a mutable variablecurrent
and assigns it to the head of the list.while let Some(node) = current
: Begins a loop that will continue untilcurrent
isNone
.println!("{}", node.data)
: Prints the data of the current node.current = node.next
: Assignscurrent
to the next node in the list.
Helpful links
Related
- Rust for loop range inclusive example
- How to iterate lines in file in Rust
- How to iterate string lines in Rust
- How to loop until error in Rust
- How to sleep in a loop in Rust
- How to iterate in pairs in Rust
- How to iterate a map in Rust
- How to iterate hashset in Rust
- How to iterate hashmap in loop in Rust
More of Rust
- How to convert a Rust slice to a fixed array?
- How to convert a slice of bytes to a string in Rust?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to escape dots with regex in Rust?
- How to convert Rust bytes to a vector of u8?
- How to get a value by key from JSON in Rust?
- How to parse JSON string in Rust?
- How to declare a matrix in Rust?
- How to calculate the sum of a Rust slice?
See more codes...