欢迎光临散文网 会员登陆 & 注册

24. 两两交换链表中的节点

2023-04-02 11:58 作者:薄荷硬糖酱  | 我要投稿

24. 两两交换链表中的节点

难度中等1779

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

 

示例 1:

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

示例 2:

输入:head = []

输出:[]

示例 3:


输入:head = [1]

输出:[1]

 


提示:


链表中节点的数目在范围 [0, 100] 内

0 <= Node.val <= 100

通过次数605,324提交次数849,278


来源:力扣(LeetCode)

链接:https://leetcode.cn/problems/swap-nodes-in-pairs

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

第一种法:

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     struct ListNode *next;

 * };

 */


struct ListNode* swapPairs(struct ListNode* head){

    if(!head)return head;

    if(!head->next)return head;

    struct ListNode *first;

    struct ListNode *second;

    struct ListNode *pre;

    struct ListNode *ans = head->next;

    pre = head;

    while(pre){

        first = pre;

        second = pre->next;

        pre = second->next;

        second->next = first;

        if(!pre) first->next = NULL;

        else first->next = pre->next;

    }

    return ans;

}

这个代码问题出在它没办法判断单数结点的情况下,second为空的状态。操作了空指针。


我自己写的代码都没有考虑到结点单复数的问题,只是一味的想特判,但是还是没用。一开始时想到了要做一个虚拟头节点但是没去做。循环的基本逻辑没错,但是总是会操作空指针。

下次要注意一个指针被赋予另一个结点的时候这个结点会不会有可能为空,若有可能就不能对它取next否则会操作空指针。

第一种法:

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     struct ListNode *next;

 * };

 */


struct ListNode* swapPairs(struct ListNode* head){

    struct ListNode* vithead = (struct ListNode*)malloc(sizeof(struct ListNode));

    vithead->next = head;

    struct ListNode* cur = vithead;

    while(cur->next&&cur->next->next){

        struct ListNode* tmp1 = cur->next;

        cur->next = cur->next->next;

        struct ListNode* tmp2 = cur->next->next;

        cur->next->next = tmp1;

        tmp1->next = tmp2;

        cur = tmp1;

    }

    return vithead->next;

}

要注意的点:

  1. 创建虚拟头节点,注意c语言要把struct 写在前面

  2. 循环判断条件,让cur能遍历到全部之后返回头指针,就是说如果最后cur的下一个结点(节点数为奇数)或cur的下一个的下一个结点(节点数为偶数)为空时退出

  3. 循环条件必须cur->next写在前面不然如果cur->next为空那么cur->next->next就是操作空指针了

  4. 循环里面的内容最好画图来解决,不然很容易出现死循环

  5. cur始终要指向需要交换的两个结点的前一个结点那里


24. 两两交换链表中的节点的评论 (共 条)

分享到微博请遵守国家法律