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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! Reverse Linked List [leetcode: reverse_linked_list](https://leetcode.com/problems/reverse-linked-list)
//!
//! Reverse a singly linked list.
//!
//! ***Example:***
//!
//! ```
//! Input: 1->2->3->4->5->NULL
//!
//! Output: 5->4->3->2->1->NULL
//! ```
//!
//! ***Follow up:***
//!
//! A linked list can be reversed either iteratively or recursively. Could you implement both?

/// # Solutions
///
/// # Approach 1: Iterative
///
/// * Time complexity: O(n)
///
/// * Space complexity: O(1)
///
/// ```rust
///
/// // 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
///     }
/// }
/// ```
///
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
}

// Definition for singly-linked list.
#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>
}

#[allow(dead_code)]
impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode {
            next: None,
            val
        }
    }
}