文章目录
- 24. 两两交换链表中的节点:
 - 样例 1:
 - 样例 2:
 - 样例 3:
 - 提示:
 
- 分析:
 - 题解:
 - rust
 - go
 - c++
 - c
 - python
 - java
 
24. 两两交换链表中的节点:
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
样例 1:

输入:
	head = [1,2,3,4]
	
输出:
	[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<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 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
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode t     = dummy;
        while (t.next != null && t.next.next != null) {
            ListNode node1 = t.next;
            ListNode node2 = node1.next;
            node1.next = node2.next;
            node2.next = node1;
            t.next = node2;
            t = node1;
        }
        return dummy.next;
    }
}
 
非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~








![[第十二届蓝桥杯/java/算法]C——卡片](https://img-blog.csdnimg.cn/8445fea992b14f3aa805385d08d75386.png)









