在上一篇学习了链表的头部插入和删除,今天尝试一下尾部的插入和删除。
一、尾部插入
在链表的尾部插入,分几种情况:
- 链表为空:直接将头指针指向新节点;否则进入第二步:
- 从头结点开始向后一直找到尾节点,将新节点挂到尾节点上。
实现时的与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不会破坏链表上节点的值。
二、尾部删除
尾部删除也分几种情况:
- 链表为空,返回None;否则进入第二步:
- 逐个向后遍历,一直找到尾部节点的前一个节点;我们称为curr;
- 判断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),
}
}
}
}
}
上面代码,注意两点:
- 一个是向后遍历找到尾部节点前一个节点的循环的写法;
- 二是对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),当数据量比较大的时候就比较耗时了。
最后,结合上一篇头部插入、删除,可以实现常见的数据结构栈、队列了!