Search code examples
algorithmperformancerustrust-tokio

How to insert a element into a LinkedList of the std::collections::LinkedList library in rust


use std::collections::LinkedList;

fn main() {
  let mut list = LinkedList::<String>::new();
  
  // Looking for something like insert(value, index)

}

I want a function that inserts the given value at the given index


Solution

  • See at54321's answer for a discussion on whether inserting into a LinkedList is a good idea in the first place (probably not).

    Now, if you are sure you want to perform that operation, you can write it yourself by combining the LinkedList::split_off, LinkedList::push_back and LinkedList::append methods:

    use std::collections::LinkedList;
    
    fn insert_at(l: &mut LinkedList<u8>, idx: usize, val: u8) {
        let mut tail = l.split_off(idx);
        l.push_back(val);
        l.append(&mut tail);
    }
    
    fn main(){
        let mut l = LinkedList::from([1, 2, 3]);
    
        insert_at(&mut l, 2, 4);
        
        let res: Vec<u8> = l.into_iter().collect();
        assert_eq!(res, vec![1, 2, 4, 3]);
    }
    

    Playground.