欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode——24. Swap Nodes in Pairs

程序员文章站 2022-07-14 08:35:05
...

1. 概述

1.1 题目

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.

1.2 解题思路

这道题是要求在给出的链表中将每对相邻的两个元素交换,不能使用额外的空间,也不能改动节点中的值。想到的第一个方法就是链表的指针操作,如下图所示

Leetcode——24. Swap Nodes in Pairs

(1)首先定义一个back和front指针,指向root伪头结点(保存头指针)和链表头结点,之后将root的下一个节点指向B

(2)将A的下一个指向C

(3)将B的下一个指向A

这样就完成了AB节点的交换

还有一种方式就是递归调用了,也是相当于把整个问题当成是一个小问题,解决了一个问题之后其它的问题都可以类似的调用解开了,推理起来不是很难

2.  编码

2.1 方法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 == nullptr) return head;
        if(nullptr == head->next) return head;
        
        //方法1
        ListNode* root = new ListNode(0);
        root->next = head;
        ListNode* back = root;
        ListNode* front = head;
        // root===>A===>B===>C
        while(front!=nullptr && nullptr != front->next)
        {
            back->next = front->next;           //root->B
            front->next = front->next->next;    //A->C
            back->next->next = front;           //B->A
            
            back = front;
            front = front->next;
        }
        head = root->next;
        
        delete root;
        root = nullptr;
        
        return head;
    }
};

2.2 方法2

/**
 * 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) return head;
        if(nullptr == head->next) return head;
              
        //方法2
        ListNode* temp = head->next;
        head->next = swapPairs(temp->next);
        temp->next = head;
        
        return temp;
    }
};