Skip to content

Commit dd4189b

Browse files
committed
add more simple solution
1 parent c16f184 commit dd4189b

File tree

1 file changed

+23
-0
lines changed
  • S0024-swap-nodes-in-pairs/src

1 file changed

+23
-0
lines changed

S0024-swap-nodes-in-pairs/src/main.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,28 @@
11
// Definition for singly-linked list.
22
use leetcode_prelude::*;
33

4+
struct Solution;
5+
use std::mem::{replace, swap};
6+
7+
impl Solution {
8+
pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
9+
let mut head = head;
10+
let mut cursor = &mut head;
11+
while cursor.is_some() && cursor.as_ref().unwrap().next.is_some() {
12+
let mut n2 = replace(&mut cursor.as_mut().unwrap().next, None);
13+
swap(
14+
&mut cursor.as_mut().unwrap().next,
15+
&mut n2.as_mut().unwrap().next,
16+
);
17+
swap(&mut n2.as_mut().unwrap().next, cursor);
18+
swap(cursor, &mut n2);
19+
cursor = &mut cursor.as_mut().unwrap().next.as_mut().unwrap().next;
20+
}
21+
22+
head
23+
}
24+
}
25+
/*
426
struct Solution;
527
628
impl Solution {
@@ -27,6 +49,7 @@ impl Solution {
2749
head
2850
}
2951
}
52+
*/
3053

3154
fn main() {
3255
let l = linkedlist![1, 2, 3, 4];

0 commit comments

Comments
 (0)