Rust链表

Rust链表

定义

由于所有权的关系,在rust中实现链表一直是一个比较困难的问题。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
   pub val: i32,
   pub next: Option<Box<ListNode>>
}

impl ListNode {
  #[inline]
  fn new(val: i32) -> Self {
    ListNode {
      next: None,
      val
    }
   }
}

内存布局

常用操作

遍历

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    //获取链表结点数
    fn get_list_node_count(head: &Option<Box<ListNode>>) -> i32 {
        let mut ptr: Option<&Box<ListNode>> = head.as_ref();
        let mut node_count: i32 = 0;

        while let Some(node) = ptr {
            node_count += 1;
            ptr = node.next.as_ref();
        }

        node_count 
    }

    //获取单链表最后节点引用
    fn get_list_last_node_ref(head: &mut Option<Box<ListNode>>) -> Option<&mut Box<ListNode>> {
        let mut ptr: Option<&mut Box<ListNode>>  = head.as_mut();  
        while let Some(node) = ptr {  
            if node.next.is_none() { 
                ptr = Some(node); 
                break; 
            }  
            ptr = node.next.as_mut();  
        }  
        ptr
    }

    // 获取第n个节点的可变引用
    fn get_list_n_node_mut_ref(head: &mut Option<Box<ListNode>>, n: i32) -> &mut Box<ListNode> {
        let mut ptr: &mut Box<ListNode> = head.as_mut().unwrap();
        for _ in 0..n {
            ptr = ptr.next.as_mut().unwrap(); 
        }
        ptr
    }

参考

  1. GitHub - WeAthFoLD/rust-too-many-lists-zhcn: 《Learn Rust With Entirely Too Many Linked Lists》 简体中文翻译
updatedupdated2024-05-102024-05-10