zl程序教程

您现在的位置是:首页 >  后端

当前栏目

力扣:24. 两两交换链表中的节点

链表节点 24 力扣 交换
2023-09-14 09:12:40 时间

24. 两两交换链表中的节点
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head)
{
    struct ListNode* shead=(struct ListNode*)malloc(sizeof(struct ListNode));
    shead->val=0;
    shead->next=head;
    struct ListNode* cur=shead;
    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;
        cur->next->next->next=tmp1;
 
        cur=cur->next->next;
    }
    return shead->next;
}