代码随想录一刷——24. 两两交换链表中的节点

使用虚拟节点来进行操作,注意cur的位置需要在每次操作的两个数值的前一位

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* dummyhead = new ListNode(0);

        dummyhead->next = head;

        ListNode* cur = dummyhead;

        //注意这里先是cur->next,而后再是cur->next->next,如果二者倒换的话,假使cur->next为空的话,那么cur->next->next是不正确的,程序会出现问题

        while(cur->next!=nullptr&& cur->next->next != nullptr)

        {

            ListNode* tmp = cur->next;

            ListNode* tmp1 = cur->next->next->next;

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

            cur->next->next = tmp;

            tmp->next = tmp1;

            cur = cur->next->next;

        }

        ListNode* result = dummyhead->next;

        delete dummyhead;

        return result;

    }

};

Python:

# Definition for singly-linked list.

# class ListNode(object):

#     def __init__(self, val=0, next=None):

#         self.val = val

#         self.next = next

class Solution(object):

    def swapPairs(self, head):

        """

        :type head: Optional[ListNode]

        :rtype: Optional[ListNode]

        """

        dummyhead = ListNode(next = head)

        cur = dummyhead

        while cur.next!=None and cur.next.next != None:

            tmp = cur.next

            tmp1 = cur.next.next.next

            cur.next = cur.next.next

            cur.next.next = tmp

            tmp.next = tmp1

            cur = cur.next.next

        return dummyhead.next

C:

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     struct ListNode *next;

 * };

 */

struct ListNode* swapPairs(struct ListNode* head)

{

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

    dummyhead->val = 0;

    dummyhead->next = head;

    struct ListNode* cur = dummyhead;

    while(cur->next != NULL && cur->next->next != NULL)

    {

        struct ListNode* tmp = cur->next;

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

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

        cur->next->next = tmp;

        tmp->next = tmp1;

        cur = cur->next->next;

    }

    struct ListNode* result = dummyhead->next;

    free(dummyhead);

    return result;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值