[−][src]Function leetcode_for_rust::cd0206_reverse_linked_list::reverse_list
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>>
Solutions
Approach 1: Iterative
-
Time complexity: O(n)
-
Space complexity: O(1)
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { if head.is_none() { return None; } let mut prev = None; let mut current = head; while let Some(mut tmp) = current.take() { let next = tmp.next.take(); tmp.next = prev.take(); prev = Some(tmp); current = next; } prev } }