Created
March 2, 2026 07:17
-
-
Save kujirahand/22af704c664b551688c7cf171f262060 to your computer and use it in GitHub Desktop.
Rustで単方向リスト
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
| // 単方向リストのノード構造体 --- (*1) | |
| #[derive(Debug)] | |
| struct Node { | |
| value: String, | |
| next: Option<Box<Node>>, | |
| } | |
| impl Node { | |
| // ノードを作成する関数 --- (*3) | |
| fn new(value: &str) -> Self { | |
| Node { | |
| value: value.to_string(), // --- (*2) | |
| next: None, | |
| } | |
| } | |
| } | |
| // リストの末尾に文字列を追加する関数 --- (*4) | |
| fn push_data(head: &mut Option<Box<Node>>, value: &str) { | |
| if head.is_none() { | |
| *head = Some(Box::new(Node::new(value))); | |
| } else { | |
| // リストの末尾のノードを探す | |
| let mut current = head.as_mut().unwrap(); | |
| loop { | |
| if current.next.is_none() { | |
| current.next = Some(Box::new(Node::new(value))); | |
| break; | |
| } else { | |
| current = current.next.as_mut().unwrap(); | |
| } | |
| } | |
| } | |
| } | |
| // リストの一覧を表示する関数 --- (*5) | |
| fn print_list(head: &Option<Box<Node>>) { | |
| let mut current = head.as_ref(); | |
| while let Some(node) = current { | |
| println!("- {}", node.value); | |
| current = node.next.as_ref(); | |
| } | |
| } | |
| // メイン関数 --- (*7) | |
| fn main() { | |
| let mut head: Option<Box<Node>> = None; | |
| // データの追加 | |
| push_data(&mut head, "りんご"); | |
| push_data(&mut head, "みかん"); | |
| push_data(&mut head, "バナナ"); | |
| // リストの一覧を表示 | |
| print_list(&head); | |
| // Rustでは自動的にメモリが解放される(Drop traitにより) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment