Categories
不学无术

LeetCode 24. Swap Nodes in Pairs

题目:https://leetcode.com/problems/swap-nodes-in-pairs/
思路:
真是个让人头晕的问题,头晕的地方在于指针,不过记住指针其实就是个地址就行了。题目的意思是奇数项和偶数项交换,先假设输入数组就是偶数个数字的,那其实就是a[i]与a[i+1]为一对一对的交换,但是由于是单链表而且不允许做值交换,只能通过改变next指针实现了。
我们假设有这么个数组/地址:

value   [1,   2,   3,   4,   5,   6]
address [0x1, 0x2, 0x3, 0x4, 0x5, 0x6]

很显然的,如果两个数的值进行交换,我们就需要找个临时变量存着,这里也是一样。本题的主要思路就是,不能乱,一对一对的来…
只看中间的3,4两项为一对,且假设其他一切都安排妥当了[2, 1, (当前对), 5, 6],那么变换后的结果是 [3]->next = [5], [4]->next = [3]并且[1]->next = [4]. 然后具体而言分下面几步:

  1. 当前工作指针curr是[3],记住[3]的后续节点[4]的位置,即temp = 0x4;
  2. 把[3]和[5]连上,即 [3]->next = temp->next = 0x5;
  3. 把[4]放到[3]前面,即temp->next = [3] (0x3);
  4. 把[2]和[4]连上,即[2]->next = temp; 所以整个环节中还需要存一个[3]的前序节点的指针(这里是0x2);
  5. 挪动指针,注意的是只要往后next一下就行了,因为目前的排序已经是[2,1, 4,3, …]了:curr = curr->next (0x5);

搞定主要部分后要注意特殊情况:0输入,1输入,奇数项输入(最后一项不处理就行)
代码:

/**
 * 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)
            return head;
        if(head->next == NULL)
            return head;
        ListNode* curr = head;
        ListNode* prev = NULL;
        head = head->next;
        ListNode* temp;
        while(curr != NULL && curr->next != NULL){
            temp = curr->next;
            if(prev != NULL) {
                prev->next = temp;
            }
            curr->next = temp->next;
            temp->next = curr;
            prev = curr;
            //Change of current node
            curr = curr->next;
        }
        return head;
    }
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.