diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 10337a7f..3b86ac6f 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -380,5 +380,30 @@ function swapPairs($head) } ``` +Rust: + +```rust +// 虚拟头节点 +impl Solution { + pub fn swap_pairs(head: Option>) -> Option> { + let mut dummy_head = Box::new(ListNode::new(0)); + dummy_head.next = head; + let mut cur = dummy_head.as_mut(); + while let Some(mut node) = cur.next.take() { + if let Some(mut next) = node.next.take() { + node.next = next.next.take(); + next.next = Some(node); + cur.next = Some(next); + cur = cur.next.as_mut().unwrap().next.as_mut().unwrap(); + } else { + cur.next = Some(node); + cur = cur.next.as_mut().unwrap(); + } + } + dummy_head.next + } +} +``` + -----------------------