Leetcode ☞ 24. Swap Nodes in Pairs ☆

24. Swap Nodes in Pairs

My Submissions
Question
Total Accepted: 84289  Total Submissions: 243534  Difficulty: Medium

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.











AC(0ms,最快一批):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
    if(!head || !head->next) 
        return head;
    
    struct ListNode* dummy, *prev, *nextNode;
    dummy = head;
    prev = nextNode = NULL;
    
    while(dummy != NULL && dummy->next != NULL){
        nextNode = dummy->next;
        dummy->next = nextNode->next;
        nextNode->next = dummy;
        if(prev)
            prev->next = nextNode;
        else
            head = nextNode;

        prev = dummy;
        dummy = dummy->next;
    }
    return head;
}

分析:

跟反转的某一种方法有点像。

此题要注意的是 第一个pair 跟之后的pair 处理不一样:之后的pair还需要跟前面已经处理好的黏起来,而第一个pair前面是没东西可粘的!所以加一个if判断是不是第一个pair













你可能感兴趣的:(Leetcode ☞ 24. Swap Nodes in Pairs ☆)