Rust实现链表(unsafe)

下面简单的用unsafe Rust完成一个三节点链表(主要原因是safe Rust的所有权让我头大)
连接,遍历的思想与C语言里的完全相同.

struct Linknode {
    data: i32,
    ptr: *const Linknode,
}
impl Linknode {
    fn new(input: i32) -> Linknode {
        Linknode {
            data: input,
            ptr: std::ptr::null(),
        }
    }
}
fn main() {
    let mut node1 = Linknode::new(1);
    let mut node2 = Linknode::new(2);
    let node3 = Linknode::new(3);
    //连接
    node1.ptr = &node2 as *const Linknode;
    node2.ptr = &node3 as *const Linknode;
    //遍历
    println!("---------------------");
    let mut p = &node1 as *const Linknode;
    unsafe{
        //当解引用裸指针时需要用unsafe代码块
        while !p.is_null()
        //没到链表结尾时
        {
            print!("{}->",(*p).data);
            p = (*p).ptr;
        }
    }
    //插入
    println!("");
    let mut new_node = Linknode::new(666);//插入新节点 data域为666
    new_node.ptr = &node3 as *const Linknode;
    node2.ptr = &new_node as *const Linknode;
    p = &node1 as *const Linknode;
    unsafe{
        //展示
        while !p.is_null()
        {
            print!("{}->",(*p).data);
            p = (*p).ptr;
        }
    }
    //删除
    println!("");
    node2.ptr = &node3 as *const Linknode;
    drop(new_node);//清理掉新的节点
    p = &node1 as *const Linknode;
    unsafe{
        //展示
        while !p.is_null()
        {
            print!("{}->",(*p).data);
            p = (*p).ptr;
        }
    }
}

运行结果如下图所示:
运行结果
需要注意的是我这里使用的裸指针类型为*const T,即裸指针指向的内容不可变,若想让data域可变应该使用*mut T 类型
两种裸指针,见Rust标准库

posted @ 2021-02-22 15:26  飞洲人飞舟魂  阅读(487)  评论(1编辑  收藏  举报
.c_ad_block { display: none !important; }