资讯专栏INFORMATION COLUMN

leetcode 24 Swap Nodes in Pairs

heartFollower / 439人阅读

摘要:最后返回头节点。同时题目要求只能占用常数空间,并且不能改变节点的值,改变的是节点本身的位置。翻转是以两个节点为单位的,我们新声明一个节点表示当前操作到的位置。每次操作结束,将指针后移两个节点即可。执行操作前要确定操作的两个节点不为空。

题目详情
Given a linked list, swap every two adjacent nodes and return its head.

题目要求输入一个链表,我们将相邻的两个节点的顺序翻转。最后返回头节点。同时题目要求只能占用常数空间,并且不能改变节点的值,改变的是节点本身的位置。

例如,
输入 1->2->3->4, 你应该返回的链表:2->1->4->3.

想法

要求返回头节点,因此我们需要新建一个节点(dummy)指向头节点,方便最后返回头节点。

翻转是以两个节点为单位的,我们新声明一个节点current表示当前操作到的位置。每次操作结束,将current指针后移两个节点即可。

执行操作前要确定操作的两个节点不为空。

简单画了一下翻转的过程

解法
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode current = dummy;
        
        while(current.next != null && current.next.next != null){
            ListNode first = current.next;
            ListNode second = current.next.next;
            
            first.next = second.next;
            second.next = first;
            current.next = second;
            current = current.next.next;
        }
        
        return dummy.next;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68792.html

相关文章

  • leetcode24 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 r...

    GT 评论0 收藏0
  • [Leetcode] Swap Nodes in Pairs Reverse Nodes in k-

    摘要:三指针法复杂度时间空间思路基本的操作链表,见注释。注意使用头节点方便操作头节点。翻转后,开头节点就成了最后一个节点。 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 ...

    TZLLOG 评论0 收藏0
  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0
  • [LintCode] Swap Nodes in Pairs

    摘要:指针为,我们选择的两个结点是和。要注意循环的边界条件,这两个结点不能为空。主要思路是先用和两个新结点去保存和两个结点。完成交换之后,连接和,并让前进至此时的结点。 Problem Given a linked list, swap every two adjacent nodes and return its head. Example Given 1->2->3->4, you sh...

    EscapedDog 评论0 收藏0
  • 【LC总结】翻转链表 Swap in Pairs, Reverse in k-Group, Reve

    摘要:注意这里,只要走到第位 Swap Nodes in Pairs For example,Given 1->2->3->4, you should return the list as 2->1->4->3. Solution public class Solution { public ListNode swapPairs(ListNode head) { if...

    Steve_Wang_ 评论0 收藏0

发表评论

0条评论

heartFollower

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<