Created
May 27, 2024 09:35
-
-
Save harryhanYuhao/8b05945c0000582e4dd6ea195cc1e29f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::{Arc, Mutex}; | |
// dummy struct for simplicity | |
struct LinkedList { | |
next: Option<Arc<Mutex<LinkedList>>>, | |
val: u32, | |
} | |
fn main() { | |
let vec_int: Vec<u32> = vec![1, 2, 3, 4, 5]; | |
let normal_res = LinkedList { next: None, val: 0 }; | |
// head pointer | |
let mut head = Arc::new(Mutex::new(normal_res)); | |
let normal_res = Arc::clone(&head); | |
for (i, val) in vec_int.iter().enumerate() { | |
// the first one is different: fill in the created LinkedList | |
if i == 0 { | |
(*head).lock().unwrap().val = *val; | |
continue; | |
} | |
// create new LinkedList and link it | |
let next = LinkedList { | |
next: None, | |
val: *val, | |
}; | |
let next = Arc::new(Mutex::new(next)); | |
(*head).lock().unwrap().next = Some(Arc::clone(&next)); | |
head = next; | |
} | |
let mut head = normal_res; | |
loop { | |
let dummy_head = Arc::clone(&head); | |
let dummy_head = dummy_head.lock().unwrap(); | |
println!("val: {}", dummy_head.val); | |
if dummy_head.next.is_none(){ | |
break; | |
} | |
head = Arc::clone(&dummy_head.next.as_ref().unwrap()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment