导航

LeetCode 24. Swap Nodes in Pairs

Posted on 2016-09-18 16:39  CSU蛋李  阅读(88)  评论(0编辑  收藏  举报

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

 

这个题目要注意的是前面两个节点的翻转和后面的节点翻转不一样,因为最前面的两个节点没有前序节点,还要注意的一点是:何时跳出!!!

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next)return head;
        ListNode* pre = head, *current = head->next,*next;
        pre->next = current->next;
        current->next = pre;
        head = current;
        if (!pre->next)return head;
        current = pre->next;
        next = current->next;
        while (current&&next)
        {
            current->next = next->next;
            next->next = current;
            pre->next = next;
            pre = current;
            if (!pre->next)return head;
            current = current->next;
            next = current->next;
        }
        return head;
    }
};