#Implementation of a LinkedList

10 messages · Page 1 of 1 (latest)

hollow gyro
#

Hi everyone, I have read implementation of a linkedlist is not intuitive, so I wanted to implement one myself. Can you also have a look and correct me if code snippets are not idiomatic or inefficient? I also wrote tests for almost every function, and all of the methods are working as expected ( I guess).

#
pub mod Node {
    #[derive(Debug, PartialEq)]
    pub struct Node<T> {
        data: T,
        next: Option<Box<Node<T>>>
    }

    impl<T> Node<T> {
        pub fn new(data: T, next: Option<Box<Node<T>>>) -> Self {
            Self {
                data: data,
                next: next
            }
        }

        pub fn get_next(&mut self) -> Option<Box<Node<T>>> {
            self.next.take()
        }

        pub fn get_next_ref(&self) -> Option<&Node<T>> {
            self.next.as_deref()
        }

        pub fn get_next_mut(&mut self) -> Option<&mut Node<T>> {
            self.next.as_deref_mut()
        }

        pub fn set_next(&mut self, next: Option<Box<Node<T>>>) {
            self.next = next;
        }

        pub fn get_value(&self) -> T 
        where T: Copy {
            self.data
        }
    }
}
sonic chasm
#

this is a valid implementation of a singly linked list, but mainly linked lists are used in low level programming are doubly linked lists or circular linked lists

#

linked lists as an idiom are rarely useful, the most notable use imo is lock free concurrency, which will probably use a custom data structure anyway

clear hazel
#

the fun stuff happens when you do doubly linked lists

hollow gyro
hollow gyro