LinkedList Deque Operations
Push and pop at both ends of std::collections::LinkedList, then append, split, and iterate lists without contiguous memory.
Code
use std::collections::LinkedList;
fn main() {
let mut list: LinkedList<&str> = LinkedList::new();
// 双端插入,不要求连续内存
list.push_back("b");
list.push_back("d");
list.push_front("a");
list.push_front("start");
println!("list: {:?}", list.iter().collect::<Vec<_>>());
println!("len: {} front: {:?} back: {:?}", list.len(), list.front(), list.back());
// pop 从两端移除并返回所有权
println!("pop_front: {:?}", list.pop_front());
println!("pop_back: {:?}", list.pop_back());
// append 把另一个链表整体接在尾部,O(1)
let mut tail = LinkedList::new();
tail.push_back("y");
tail.push_back("z");
list.append(&mut tail);
println!("after append: {:?}", list.iter().collect::<Vec<_>>());
println!("tail is empty: {}", tail.is_empty());
// split_off 从指定位置切开,后半段成为新链表
let second_half = list.split_off(2);
println!("first half: {:?}", list.iter().collect::<Vec<_>>());
println!("second half: {:?}", second_half.iter().collect::<Vec<_>>());
// contains 需要线性扫描,这正是链表的代价
list.push_back("c");
println!("contains b: {}", list.contains(&"b"));
}How the snippet works
Count the function main as the entire surface area of LinkedList Deque Operations.
Using it
The run emits 9 labeled sections — list:, len:, pop_front:, pop_back:, after append:, tail is empty:, first half:, second half:, contains b: — one per step.
Key statements
let mut list: LinkedList<&str> = LinkedList::new();
let second_half = list.split_off(2);
let mut tail = LinkedList::new();
Interactive Tools for This Topic
FAQ
- What does LinkedList Deque Operations print when run?
- Execute the whole file; each printed line is prefixed with a label like `list:`, `len:`, `pop_front:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.