论坛首页 入门技术论坛

[LeetCode] Swap Nodes in Pairs

浏览 1356 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-15  

 

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode* newhead = head->next;
        ListNode* prev = NULL, *cur1 = head, *cur2 = head->next;;
        prev = cur1;
        cur1->next = cur2->next;
        cur2->next = cur1;
        while (prev->next != NULL && prev->next->next != NULL) {
            cur1 = prev->next;
            cur2 = cur1->next;
            
            prev->next = cur2;
            cur1->next = cur2->next;
            cur2->next = cur1;
            prev = cur1;
        }
        return newhead;
    }
};

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics