003 add functions to the linked list by learning rust from the linked list



Video address:www.bilibili.com/video/av78062009/
Relevant source code:github.com/anonymousGiga/Rust-link…


In the previous section, we basically determined the layout of the linked list. Next, we will implement the response function of the linked list.

For linked lists, the most basic functions are:

The new // new function is a function that creates a linked list
Push // function for adding elements
Pop // function of pop-up element


The implementation is as follows:

impl List {
    pub fn new() -> Self {
        List { head: Link::Empty }


The implementation is as follows:

impl List {
    pub fn push(&mut self, elem: i32) {
        let node = Box::new(Node {
            elem: elem,
            next: mem::replace(&mut self.head, Link::Empty),

        self.head = Link::More(node);


Unlike the push function, the pop function needs to consider the case when the linked list is empty, so we consider using option for the return value of the pop function. The implementation code is as follows:

impl List {
    pub fn pop(&mut self) -> Option<i32> {
        match mem::replace(&mut self.head, Link::Empty) {
            Link::Empty => None,
            Link::More(node) => {
                self.head = node.next;

So far, we have written several basic functions of the linked list!

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed

Recommended Today

Infinite scroll list

Complexities of an infinite scroller Code example of implementation There are many usage scenarios for infinite scrolling, and some difficulties need to be paid attention to. For example, the links in the footer cannot be accessed because the content keeps pushing the footer away; How do you handle resizing events when the phone changes from […]