Adding an append method to a singly linked list

后端 未结 3 1431
死守一世寂寞
死守一世寂寞 2020-11-29 13:40

I was looking through the singly linked list example on rustbyexample.com and I noticed the implementation had no append method, so I decided to try and impleme

3条回答
  •  盖世英雄少女心
    2020-11-29 14:00

    As the len method is implemented recursively, I have done the same for the append implementation:

    fn append(self, elem: u32) -> List {
        match self {
            Cons(current_elem, tail_box) => {
                let tail = *tail_box;
                let new_tail = tail.append(elem);
    
                new_tail.prepend(current_elem)
            }
            Nil => {
                List::new().prepend(elem)
            }
        }
    }
    

    One possible iterative solution would be to implement append in terms of prepend and a reverse function, like so (it won't be as performant but should still only be O(N)):

    // Reverses the list
    fn rev(self) -> List {
        let mut result = List::new();
        let mut current = self;
        while let Cons(elem, tail) = current {
            result = result.prepend(elem);
            current = *tail;
        }
    
        result
    }
    
    fn append(self, elem: u32) -> List {
        self.rev().prepend(elem).rev()
    }
    

提交回复
热议问题