qingcheng奕  

https://oj.leetcode.com/problems/swap-nodes-in-pairs/

链表的处理

/**
 * 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) {
        ListNode *dummy = new ListNode(-1);
        if(head == NULL)
            return dummy->next;
        
        dummy->next = head;
        
        ListNode *tail = dummy;
        
        ListNode *current = head;
        ListNode *second = head->next;
        while(current && second)
        {
            tail->next = second;
            current->next = second->next;
            second->next = current;
            
            current = current->next;
            if(current == NULL)
                break;
            second = current->next;
            tail = tail->next;
            tail = tail->next;
            
        }
        return dummy->next;
    }
};

 

posted on 2014-08-16 20:57  qingcheng奕  阅读(116)  评论(0编辑  收藏  举报