Open jason89521 opened 3 months ago
Link: https://leetcode.com/problems/reverse-linked-list/description/
// 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 // } // } // } impl Solution { pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut current = head?; let mut prev = None; let mut next = current.next; while next.is_some() { current.next = prev; prev = Some(current); current = next.unwrap(); next = current.next; } current.next = prev; Some(current) } }
Time complexity: O(n)
Can use while let next time trying to resolve this problem.
while let
Practice Dates
Description
Link: https://leetcode.com/problems/reverse-linked-list/description/
Solution
Performance
Time complexity: O(n)