-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathreverse-linked-list.rs
45 lines (42 loc) · 1.06 KB
/
reverse-linked-list.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
// 206. Reverse Linked List
// 🟢 Easy
//
// https://leetcode.com/problems/reverse-linked-list/
//
// Tags: Linked List - Recursion
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
struct Solution;
impl Solution {
/// Travel through the list reversing the pointer between each node and its
/// next.
///
/// Time complexity: O(n) - We visit each node.
/// Space complexity: O(1) - We use constant extra space.
///
/// Runtime 1 ms Beats 78.38%
/// Memory 2.37 MB Beats 85.47%
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let (mut prev, mut curr) = (None, head);
while let Some(mut node) = curr {
curr = node.next;
node.next = prev;
prev = Some(node);
}
prev
}
}
// Tests.
fn main() {
println!("[92m» All tests passed![0m")
}