LEETCODE(力扣) 24. 两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:

输入:head = []
输出:[]
示例 3:

输入:head = [1]
输出:[1]

提示:

链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100

自解

image
(内存击败是个玄学多运行几次每次都不一样...)
交换两个链表必定牵扯到前面的那一个链表,因此可使用一个Dummy节点插到链表头,便于交换
例:1->2->3->4 如果交换3、4必需对2->next进行修改,而首结点则没有更前面的节点,代码逻辑上需要对首结点进行特殊判断
加入dummy后:dummy->1->2->3->4
加入dummy后从dummy开始进行判断,每次的while循环只要连续两个next并交换就行,而不用对首结点专门写一个逻辑

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

struct ListNode* swapPairs(struct ListNode* head) {
    struct ListNode Dummy,*temp=NULL,*temp1=NULL;
    Dummy.next=head;
    head=&Dummy;
    while(head->next&&head->next->next)
    {
        temp=head->next->next->next;
        head->next->next->next=head->next;
        temp1=head->next->next;
        head->next->next=temp;
        head->next=temp1;
        head=head->next->next;
    }
    return Dummy.next;
}

力扣解

方法二:迭代,就是上方自解的思路

struct ListNode* swapPairs(struct ListNode* head) {
    struct ListNode dummyHead;
    dummyHead.next = head;
    struct ListNode* temp = &dummyHead;
    while (temp->next != NULL && temp->next->next != NULL) {
        struct ListNode* node1 = temp->next;
        struct ListNode* node2 = temp->next->next;
        temp->next = node2;
        node1->next = node2->next;
        node2->next = node1;
        temp = node1;
    }
    return dummyHead.next;
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/swap-nodes-in-pairs/solutions/444474/liang-liang-jiao-huan-lian-biao-zhong-de-jie-di-91/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2025-04-28 17:35  Osen  阅读(9)  评论(0)    收藏  举报