■ Box<T> 구조체를 사용해 단방향 연결 리스트를 만드는 방법을 보여준다.
▶ 예제 코드 (RS)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
pub struct Node { data : isize, link : Option<Box<Node>> } pub struct LinkedList { head : Option<Box<Node>> } impl LinkedList { pub fn new() -> Self { return Self { head : None }; } pub fn insert_first(&mut self, value : isize) { let node_box_option : Option<Box<Node>> = self.head.take(); let new_node : Node = Node { data : value, link : node_box_option }; let new_node_box : Box<Node> = Box::new(new_node); self.head = Some(new_node_box); } pub fn push(&mut self, value : isize) { let new_node : Node = Node { data : value, link : None }; match self.head { None => { let node_box : Box<Node> = Box::new(new_node); self.head = Some(node_box); }, Some(ref mut head) => { let mut current_node_box : &mut Box<Node> = head; loop { match current_node_box.link { None => { let new_node_box : Box<Node> = Box::new(new_node); current_node_box.link = Some(new_node_box); break; }, Some(ref mut next) => current_node_box = next, } } } } } pub fn get(&self, index : isize) -> Option<isize> { match self.head { None => return None, Some(ref top) => { let mut current_node_box : &Box<Node> = top; let mut current_index : isize = 0; loop { if current_index == index { return Some(current_node_box.data); } match current_node_box.link { None => return None, Some(ref next) => current_node_box = next, } current_index += 1; } } } } } fn main() { let mut linked_list : LinkedList = LinkedList::new(); linked_list.push(300); linked_list.push(400); linked_list.insert_first(200); linked_list.insert_first(100); println!("{}", linked_list.get(0).unwrap()); println!("{}", linked_list.get(1).unwrap()); println!("{}", linked_list.get(2).unwrap()); println!("{}", linked_list.get(3).unwrap()); } /* 100 200 300 400 */ |