017 通过链表学Rust之实现元素添加

Rust
380
0
0
2022-05-01

介绍

视频地址:www.bilibili.com/video/av78062009/

相关源码:github.com/anonymousGiga/Rust-link...

详细内容

在上一节我们定义了我们的双链表,本节我们来给双链表创建new函数和pushfront函数。

new

impl<T> Node<T> {
fn new(elem: T) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Node {
elem: elem,
prev: None,
next: None,}))}
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None, tail: None }}
}

push_front

下面我们增加添加元素的函数,如下:

pub fn push_front(&mut self, elem: T) {let node = Node::new(elem);
match self.head.take() {Some(head) => {
head.borrow_mut().prev = Some(node.clone());
node.borrow_mut().next = Some(head);
self.head = Some(node);}None => {
self.tail = Some(node.clone());
self.head = Some(node);}}}

完整代码

添加后的完整代码如下:

use std::rc::Rc;
use std::cell::RefCell;
pub struct List<T> {
head: Link<T>,
tail: Link<T>,
}
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
struct Node<T> {
elem: T,
next: Link<T>,
prev: Link<T>,
}
impl<T> Node<T> {
fn new(elem: T) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(Node {
elem: elem,
prev: None,
next: None,}))}
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None, tail: None }}
pub fn push_front(&mut self, elem: T) {let node = Node::new(elem);
match self.head.take() {Some(head) => {
head.borrow_mut().prev = Some(node.clone());
node.borrow_mut().next = Some(head);
self.head = Some(node);}
None => {
self.tail = Some(node.clone());
self.head = Some(node);}}}
}