码迷,mamicode.com
首页 > 其他好文 > 详细

Swap Nodes in Pairs

时间:2017-03-18 23:46:22      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:交换   count   amp   while   des   bsp   head   node   记录   

 思路一:记录遍历列表过程中奇偶性,然后进行交换

/**
 * 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 == nullptr || head->next == nullptr)
            return head;
            
        ListNode dummy(-1);
        dummy.next = head;
        ListNode *cur = head->next;
        ListNode *curLeft = &dummy;
        
        int count = 2;
        while(cur)
        {
            if(count % 2 == 0)
            {
                curLeft->next->next = cur->next;
                cur->next = curLeft->next;
                
                ListNode *tmp = curLeft->next;
                curLeft->next = cur;
                curLeft = tmp;
                cur = cur->next;
            }
            
            cur = cur->next;
            ++count;
        }
        
        return dummy.next;
    }
};

思路二:上面思路中使用两个指针,但实际使用三个指针会方便很多

/**
 * 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 == nullptr || head->next == nullptr)
            return head;
            
        ListNode dummy(-1);
        dummy.next = head;
        
        for(ListNode *prev = &dummy, *cur=head, *next=head->next; next; prev=cur, cur=cur->next, next=cur ? cur->next:nullptr)
        {
            cur->next = next->next;
            next->next = cur;
            prev->next = next;
        }
        
        return dummy.next;
    }
};

 

Swap Nodes in Pairs

标签:交换   count   amp   while   des   bsp   head   node   记录   

原文地址:http://www.cnblogs.com/chengyuz/p/6576468.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!