024 Swap Nodes in Pairs[M]

1 题目描述

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

Your algorithm should use only constant space. You may
not modify the values in the list, only nodes itself can be changed.

难度:Medium

2 题目样例

For example,

Given 1->2->3->4, you should return the list as 2->1->4->3.

3 题意分析

这道题目是想让你成对交换链表中的节点。

不算难,属于基本的链表题目。

4 思路分析

可以利用回溯的思想,每次都递归遍历到链表末尾,先交换链表最后两个节点,然后依次向前操作。

用递归写出来的代码十分简洁。

代码实现如下:

class Solution 

{
    
public:
    
    ListNode* swapPairs(ListNode* head) 
    
    {
        if (!head || !head->next) return head;
        
        ListNode *t = head->next;
        
        head->next = swapPairs(head->next->next);
        
        t->next = head;
        
        return t;
    }
};

也可以利用迭代的方法进行实现,直接按照题目说的去操作就行了。

5 后记

最近的题目多数都是数据结构题目而不是算法题目欸……

数据结构蒟蒻表示瑟瑟发抖,并且留下了悔恨(当年没好好学)的眼泪。QAQ

    原文作者:Lolita
    原文地址: https://zhuanlan.zhihu.com/p/33862058
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞