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

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;
}

猜你喜欢

转载自blog.csdn.net/congfen214/article/details/129542824