输出:
[2,1,4,3]
### 样例 2:
输入:
head = []
输出:
[]
### 样例 3:
输入:
head = [1]
输出:
[1]
### 提示:
* 链表中节点的数目在范围 `[0, 100]` 内
* `0 <= Node.val <= 100`
---
## 分析:
* 面对这道算法题目,二当家的陷入了沉思。
* 利用指针做位置交换,递归或者遍历处理,直接上就行了。
* 递归还是比较直观,简单。
* 遍历也不难,但是单向链表需要前结点来指向当前结点,所以需要一个哑结点来统一处理,手工管理内存的话,需要最后释放掉哑结点。
---
## 题解:
### rust
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn swap_pairs(head: Option<Box>) -> Option<Box> {
let mut dummy = ListNode::new(0);
let mut t = &mut dummy;
t.next = head;
while t.next.is_some() && t.next.as_ref().unwrap().next.is_some() {
let mut node1 = t.next.take();
let mut node2 = node1.as_mut().unwrap().next.take();
node1.as_mut().unwrap().next = node2.as_mut().unwrap().next.take();
node2.as_mut().unwrap().next = node1;
t.next = node2;
t = t.next.as_mut().unwrap().next.as_mut().unwrap();
}
return dummy.next;
}
}
---
### go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapPairs(head *ListNode) *ListNode {
dummy := &ListNode{0, head}
t := dummy
for t.Next != nil && t.Next.Next != nil {
node1 := t.Next
node2 := node1.Next
node1.Next = node2.Next
node2.Next = node1
t.Next = node2
t = node1
}
return dummy.Next
}
---
### c++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy = ListNode(0, head);
ListNode *t = &dummy;
while (t->next != nullptr && t->next->next != nullptr) {
ListNode *node1 = t->next;
ListNode *node2 = node1->next;
node1->next = node2->next;
node2->next = node1;
t->next = node2;
t = node1;
}
return dummy.next;
}
};
---
### c
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode *dummy = malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode *t = dummy;
while (t->next != NULL && t->next->next != NULL) {
struct ListNode *node1 = t->next;
struct ListNode *node2 = node1->next;
node1->next = node2->next;
node2->next = node1;
t->next = node2;
t = node1;
}
head = dummy->next;
free(dummy);
return head;
}
---
### python
Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head)
t = dummy
while t.next and t.next.next:
node1 = t.next
node2 = node1.next
node1.next = node2.next
node2.next = node1
t.next = node2
t = node1
return dummy.next
---
### java
183

被折叠的 条评论
为什么被折叠?



