[Leetcode] Swap Nodes in Pairs

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Swap Nodes in Pairs相关的知识,希望对你有一定的参考价值。

Swap Nodes in Pairs 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/swap-nodes-in-pairs/description/


Description

Given a linked list, swap every two adjacent nodes and return its head.

Example

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.

Solution


class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL)
            return NULL;
        ListNode *tempHead = new ListNode(0);
        tempHead -> next = head;
        ListNode* front = tempHead;
        ListNode *node1, *node2;
        while (front -> next && front -> next -> next) {
            node1 = front -> next;
            node2 = node1 -> next;
            front -> next = node2;
            node1 -> next = node2 -> next;
            node2 -> next = node1;
            front = node1;
        }
        ListNode* res = tempHead -> next;
        delete tempHead;
        return res;
    }
};

解题描述

这道题题意是将一个链表中每相邻的一对节点交换位置(已经交换过位置的不再交换)。主要的想法是,每次有三个指针frontnode1node2,在链表中是以front -> node1 -> node2的顺序排列,这里主要要做的就是交换node1node2的位置,使这段链表变成front -> node2 -> node1,之后将node1赋值给front即可开始下一步交换。

另外这里用到了一个临时链表头tempHead来指向原来的head,便于给front赋初始值,并且在返回新链表头的时候可以快速找到。


以上是关于[Leetcode] Swap Nodes in Pairs的主要内容,如果未能解决你的问题,请参考以下文章

leetcode:Swap Nodes in Pairs

LeetCode - 24. Swap Nodes in Pairs

LeetCode 24 Swap Nodes in Pairs

Leetcode24. Swap Nodes in Pairs

Leetcode24. Swap Nodes in Pairs

Leetcode 24——Swap Nodes in Pairs