Rust学习笔记(14)——struct、Option和Box组合应用实现单向链表之二

本文介绍了如何在单向链表中进行尾部插入和删除操作。通过匹配Option的as_mut()方法,实现了在链表为空或非空时的尾部插入,并详细解释了代码的关键点。尾部删除部分,通过遍历找到尾部节点的前一个节点,进行删除操作。测试代码验证了功能的正确性,展示了链表在不同状态下的变化。虽然效率较低(时间复杂度为O(N)),但这些操作为实现栈和队列奠定了基础。
摘要由CSDN通过智能技术生成

在上一篇学习了链表的头部插入和删除,今天尝试一下尾部的插入和删除。

一、尾部插入

在链表的尾部插入,分几种情况:

  1. 链表为空:直接将头指针指向新节点;否则进入第二步:
  2. 从头结点开始向后一直找到尾节点,将新节点挂到尾节点上。

实现时的与C的区别在于向后的遍历找到尾部节点,因为所有权的限制,不能像C语言那样写:

curr = curr->next;

完整代码如下:

impl BoxedLinkedList {
    fn push_back(&mut self, value: i32) {
        let new_node = Node::new(value);
        match self.head.as_mut() {
            None => self.head = Some(new_node),
            Some(mut curr) => {
                while curr.next.is_some() {
                    curr = curr.next.as_mut().unwrap();
                }
                curr.link(new_node);
            }
        }
    }
}

上述代码的关键点是Option的as_mut()方法,获取对Option内部值的引用,同时因为as_mut()方法返回新的Option,所以对其结果进行unwrap不会破坏链表上节点的值。

二、尾部删除

尾部删除也分几种情况:

  1. 链表为空,返回None;否则进入第二步:
  2. 逐个向后遍历,一直找到尾部节点的前一个节点;我们称为curr;
  3. 判断curr.next的值,根据情况对其进行删除操作;
impl BoxedLinkedList {
    fn pop_back(&mut self) -> Option<i32> {
        match self.head.as_mut() {
            None => None,
            Some(mut curr) => {
                while curr.next.is_some() && curr.next.as_ref().unwrap().next.is_some() {
                    curr = curr.next.as_mut().unwrap();
                }
                match curr.next {
                    Some(_) => Some(curr.next.take().unwrap().val),
                    None => Some(self.head.take().unwrap().val),
                }
            }
        }
    }
}

上面代码,注意两点:

  1. 一个是向后遍历找到尾部节点前一个节点的循环的写法;
  2. 二是对curr.next的判断,当链表只存在一个节点也就是头结点的操作;

三、测试运行

测试代码如下:

fn main() {
    let mut list = BoxedLinkedList::new();
    for i in 1..4 {
        list.push_back(i);
    }

    list.display();

    println!();

    while !list.is_empty() {
        let v = list.pop_back().unwrap();
        println!("pop '{}' from the tail of list", v);
        print!("now list is : ");
        list.display();
    }
}

输出如下:

BoxedLinkedList { head: Some(Node { val: 1, next: Some(Node { val: 2, next: Some(Node { val: 3, next: None }) }) }) }

pop '3' from the tail of list
now list is : BoxedLinkedList { head: Some(Node { val: 1, next: Some(Node { val: 2, next: None }) }) }
pop '2' from the tail of list
now list is : BoxedLinkedList { head: Some(Node { val: 1, next: None }) }
pop '1' from the tail of list
now list is : BoxedLinkedList { head: None }

OK!It works! 当然,对于单向链表且只有头指针的情况来说,尾部插入、删除的效率比较低,每次都要遍历找到尾部节点,时间复杂度为是O(N),当数据量比较大的时候就比较耗时了。

最后,结合上一篇头部插入、删除,可以实现常见的数据结构栈、队列了!

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值