LeetCode //C - 24. Swap Nodes in Pairs

本文介绍了如何在不改变链表节点值的情况下,通过使用哑节点处理边缘情况,迭代链表并调整next指针来实现每两个相邻节点的交换。解决方案适用于各种链表,包括空链表和单节点链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)
 

Example 1:

在这里插入图片描述

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

Constraints:
  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

From: LeetCode
Link: 24. Swap Nodes in Pairs


Solution:

Ideas:

This function uses a “dummy” node to handle edge cases where the head of the list needs to be swapped. It then iterates through the list, swapping pairs of nodes by adjusting their next pointers. It’s designed to handle lists of any size, including the edge cases of empty lists or lists with a single node, as per the constraints mentioned.

Code:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* swapPairs(struct ListNode* head) {
    // If the list is empty or has only one node, there's nothing to swap.
    if (head == NULL || head->next == NULL) {
        return head;
    }
    
    // Initialize a 'dummy' node, which points to the head of the list.
    // This helps in simplifying the swap logic for the head node.
    struct ListNode dummy;
    dummy.next = head;
    
    // Initialize 'prev' to start with the 'dummy' node.
    struct ListNode* prev = &dummy;
    
    // Loop as long as there are at least two nodes to swap.
    while (prev->next != NULL && prev->next->next != NULL) {
        // Initialize 'first' and 'second' to the two nodes to swap.
        struct ListNode* first = prev->next;
        struct ListNode* second = first->next;
        
        // Perform the swap by adjusting the 'next' pointers.
        first->next = second->next;
        second->next = first;
        prev->next = second;
        
        // Move 'prev' two nodes ahead for the next pair of swaps.
        prev = first;
    }
    
    // The 'dummy' node's next points to the new head of the list after swaps.
    return dummy.next;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值