Merhaba sevgili rust severler,
Rust ile bir linked list örneği kodlamaya çalışıyorum ancak get() metodunda fena takıldım. Bu metotta verilen index'teki elemana erişmeyi amaçlamıştım.
fn get(&mut self, index: u32) -> Option<T> {
if let Some(mut current) = self.head.take() {
for i in 0..index {
let next = current.borrow_mut().next.unwrap();
}
None
}
else {
None
}
}
Rc, RefCell gibi yapıları araştırdım ancak sanırım tam kafama yatmadı. Sanırım bu yüzden linked list'in içinde döngüyle gezmeyi bir türlü yapamadım.
Kodun tamamı burada :
mod test;
use std::cell::{Ref, RefCell, RefMut};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
#[derive(Debug)]
struct Node<T> {
pub next: Link<T>,
pub back: Link<T>,
pub value: T
}
pub trait LinkedListTrait<T> {
fn add(&mut self, value: T);
fn get(&mut self, index: u32) -> Option<T>;
fn delete(index: u32);
fn update(index: u32, new_value: T);
}
#[derive(Debug)]
pub struct LinkedList<T> {
size: u32,
head: Link<T>,
tail: Link<T>
}
impl<T> LinkedList<T> {
pub fn new() -> Self {
LinkedList {
size: 0,
head: None,
tail: None
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> u32 {
self.size
}
}
impl<T> LinkedListTrait<T> for LinkedList<T> {
fn add(&mut self, value: T) {
let node = Rc::new(RefCell::new(
Node {
next: None,
back: None,
value
}));
if let Some(old) = self.tail.take() {
old.borrow_mut().next = Some(node.clone());
node.borrow_mut().back = Some(old);
}
else {
self.head = Some(node.clone());
}
self.size += 1;
self.tail = Some(node.clone());
}
fn get(&mut self, index: u32) -> Option<T> {
if let Some(mut current) = self.head.take() {
for i in 0..index {
let next = current.borrow_mut().next.unwrap();
}
None
}
else {
None
}
}
fn delete(index: u32) {
todo!()
}
fn update(index: u32, new_value: T) {
todo!()
}
}
Yardımlarınız için şimdiden teşekkürler