jason89521 / leetcode_note

0 stars 0 forks source link

206. Reverse Linked List #3

Open jason89521 opened 3 months ago

jason89521 commented 3 months ago

Practice Dates

Description

Link: https://leetcode.com/problems/reverse-linked-list/description/

Solution

// 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)
    }
}

Performance

Time complexity: O(n)

jason89521 commented 3 months ago

Can use while let next time trying to resolve this problem.