24. Swap Nodes in Pairs

Total Accepted: 99965  Total Submissions: 281854  Difficulty: Easy

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.

Subscribe to see which companies asked this question

Hide Tags
  Linked List
Hide Similar Problems
  (H) Reverse Nodes in k-Group

分析:

如同链表的逆转一样,本题是三指针遍历,注意整个过程的规律即可,特别要注意不但要交换两个节点,还要连接前一对节点,比如2->1->3->4,把3和4交换后,1实际上并没有指向4,程序中通过pPre指针记录了节点1,将其连接交换后的4!具体见代码!

<LeetCode OJ> 206. Reverse Linked List

/**
 * 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==NULL|| head->next==NULL )
            return head;
        ListNode* pPre=head;
        ListNode* pcurSwap1=head;
        ListNode* pcurSwap2=head->next;
        head=head->next;
        while(pcurSwap1!=NULL && pcurSwap2!=NULL)
        {
           //连接链表
           pPre->next=pcurSwap2;
           //交换当前节点
           pcurSwap1->next=pcurSwap2->next;
           pcurSwap2->next=pcurSwap1;
           //准备下一对(必须均存在)
           pPre=pcurSwap1;
           pcurSwap1=pcurSwap1->next;
           if(pcurSwap1!=NULL)
                pcurSwap2=pcurSwap1->next;
        }
        return head;
    }
};


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51532493

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,C++,算法,链表,面试)