现在的位置: 首页 > 综合 > 正文

LeetCode题解:Swap Nodes in Pairs

2019年07月24日 ⁄ 综合 ⁄ 共 741字 ⁄ 字号 评论关闭

Swap Nodes in Pairs

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)
            return nullptr;
    
        ListNode* nh = new ListNode(0);
        nh->next = head;
        
        ListNode* h0 = nh;
        ListNode* h1 = head;
        ListNode* h2 = head->next;
        
        while(h2 != nullptr)
        {
            h1->next = h2->next;
            h2->next = h1;
            h0->next = h2;
            
            h0 = h1;
            h1 = h1->next;
            h2 = (h1 ? h1->next : nullptr);
        }
        h0 = nh->next;
        
        delete nh;
        return h0;
    }
};

抱歉!评论已关闭.