Leetcode——24. Swap Nodes in Pairs

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 解题思路

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


(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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值