Skip to content

Commit fe04567

Browse files
committed
feat(linked-list): 206_reverse_linked_list.rs
1 parent 9981791 commit fe04567

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,9 @@ so that you can use `just tf TEST` command to test.
124124
| - | - | - |
125125
| 121. Best Time to Buy and Sell Stock | Easy | [121_best_time_to_buy_and_sell_stock.rs](./tests/121_best_time_to_buy_and_sell_stock.rs) |
126126
| 3. Longest Substring Without Repeating Characters | Medium | [3_longest_substring_without_repeating_characters.rs](./tests/3_longest_substring_without_repeating_characters.rs) |
127+
128+
### Linked List
129+
130+
| Problem | Difficulty | Solution |
131+
| - | - | - |
132+
| 206. Reverse Linked List | Easy | [206_reverse_linked_list.rs](./tests/206_reverse_linked_list.rs) |

tests/206_reverse_linked_list.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// 206. Reverse Linked List
2+
// https://leetcode.com/problems/reverse-linked-list/description/
3+
// Topics: Linked List.
4+
// Difficulty: Easy.
5+
6+
#[test]
7+
fn test_206_reverse_linked_list() {}
8+
9+
#[derive(Debug)]
10+
pub struct Solution;
11+
12+
// ---------------------------------
13+
// copy to leetcode starts from here
14+
// ---------------------------------
15+
16+
// Definition for singly-linked list.
17+
#[derive(PartialEq, Eq, Clone, Debug)]
18+
pub struct ListNode {
19+
pub val: i32,
20+
pub next: Option<Box<ListNode>>,
21+
}
22+
23+
// impl ListNode {
24+
// #[inline]
25+
// fn new(val: i32) -> Self {
26+
// ListNode { next: None, val }
27+
// }
28+
// }
29+
30+
impl Solution {
31+
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
32+
let mut prev: Option<Box<ListNode>> = None;
33+
let mut curr: Option<Box<ListNode>> = head;
34+
35+
while let Some(mut boxed_node) = curr {
36+
curr = boxed_node.next;
37+
boxed_node.next = prev;
38+
prev = Some(boxed_node);
39+
}
40+
41+
prev
42+
}
43+
}

0 commit comments

Comments
 (0)