From 077bf2f4aa4c2bb3ccff9b9a0f6db640df7d977e Mon Sep 17 00:00:00 2001 From: lsy Date: Tue, 15 Oct 2024 01:01:11 +0800 Subject: [PATCH] =?UTF-8?q?=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/code/link.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 rust/code/link.rs diff --git a/rust/code/link.rs b/rust/code/link.rs new file mode 100644 index 0000000..4679da6 --- /dev/null +++ b/rust/code/link.rs @@ -0,0 +1,56 @@ +use std::cell::RefCell; +use std::rc::Rc; + +struct Link { + value: String, + next:Option>>, + back:Option>> +} + +impl Link { + fn init(content:&str) -> Option>> { + let link=Rc::new(RefCell::new(Link{value:String::from(content),next:None,back:None})); + link.borrow_mut().next = Some(Rc::clone(&link)); + link.borrow_mut().back = Some(Rc::clone(&link)); + Some(link) + } + fn add(old_link:Option>>,content:&str) -> Option>> { + let old_link_ref=old_link.as_ref(); + let new_link=Rc::new(RefCell::new(Link{ + value:String::from(content), + next:Some(Rc::clone(old_link_ref?.borrow().next.as_ref()?)), + back:Some(Rc::clone(old_link_ref?)) + })); + + let back_link=old_link_ref?.borrow().back.clone()?; + if Rc::ptr_eq(old_link_ref?, old_link_ref?.borrow().back.as_ref()?) { + back_link.borrow_mut().back = Some(Rc::clone(&new_link)); + } + back_link.borrow_mut().next = Some(Rc::clone(&new_link)); + Some(new_link) + } + fn del(link:Option>>) -> Option>> { + let link_ref=link.clone()?; + let back_link=link_ref.borrow().back.clone()?; + let next_link=link_ref.borrow().next.clone()?; + if Rc::ptr_eq(&link_ref, &next_link) { + drop(link); + None + }else { + back_link.borrow_mut().next=Some(Rc::clone(&next_link)); + next_link.borrow_mut().back=Some(Rc::clone(&back_link)); + Some(next_link) + } + } + +} + +fn main() { + let link=Link::init("lsy"); + let new_link=Link::add(link,"input"); + let n_n_link=Link::del(new_link); + let n_n_nlink=Link::del(n_n_link); + if let None=n_n_nlink { + println!("删除成功") + } +} \ No newline at end of file