-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.rs
66 lines (60 loc) · 1.41 KB
/
main.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
59
60
61
62
63
64
65
66
// 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 swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut dummy = ListNode::new(0);
let mut pre = &mut dummy;
let mut cur = head;
while let Some(mut n1) = cur {
cur = n1.next.take();
if let Some(mut n2) = cur {
cur = n2.next.take();
n2.next = Some(n1);
pre.next = Some(n2);
pre = pre.next.as_mut().unwrap().next.as_mut().unwrap();
} else {
pre.next = Some(n1);
pre = pre.next.as_mut().unwrap();
}
}
dummy.next
}
}
struct Solution;
#[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 }
}
}
fn main() {
let mut n1 = ListNode::new(1);
let mut n2 = ListNode::new(2);
let mut n3 = ListNode::new(3);
let n4 = ListNode::new(4);
n3.next = Some(Box::new(n4));
n2.next = Some(Box::new(n3));
n1.next = Some(Box::new(n2));
let head = Some(Box::new(n1));
let result = Solution::swap_pairs(head);
println!("result = {:?}", result);
}