0
点赞
收藏
分享

微信扫一扫

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

爱做梦的老巫婆 2022-03-23 阅读 63

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

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

struct ListNode* swapPairs(struct ListNode* head){
    if(head == NULL)
    {
        return NULL;
    }
    struct ListNode* cur = head;
    struct ListNode* newHead = NULL;
    struct ListNode* tail = NULL;
    while(cur != NULL)
    {
        struct ListNode* curNext = cur->next;
        if(curNext == NULL) 
        {
          if(newHead != NULL) {
            tail ->next = cur;
            tail =  tail ->next;
          }
          else
          {
              newHead = cur;
              tail = newHead;
          }
         break;
        }
        if(tail == NULL) {
            newHead = curNext;
            tail = newHead;
            curNext = curNext->next;
            tail->next = cur;
            tail = tail->next;
        }
        else
        {
            tail->next = curNext;
            tail =tail->next;
            curNext = curNext->next;
            tail->next = cur;
            tail =tail->next;
        }
        cur = curNext;
    }
    tail->next = NULL;
    return newHead;
}
举报

相关推荐

0 条评论