-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfan-zhuan-lian-biao-lcof.rs
58 lines (46 loc) · 1.29 KB
/
fan-zhuan-lian-biao-lcof.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
46
47
48
49
50
51
52
53
54
55
56
57
58
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct 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_list1(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut vals = vec![];
let mut head = head;
while head.is_some() {
let mut h = head.unwrap();
vals.push(h.val);
head = h.next.take();
}
let mut r = None;
let mut current = &mut r;
while let Some(val) = vals.pop() {
current.replace(Box::new(ListNode::new(val)));
current = &mut current.as_mut().unwrap().next;
}
r
}
pub fn reverse_list(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
if head.is_none() {
return head;
}
let mut next = head.as_mut().unwrap().next.take();
while let Some(n) = next.as_mut() {
let new_head = n.next.take();
n.next = head;
head = next;
next = new_head;
}
head
}
}