zoukankan      html  css  js  c++  java
  • LeetCode24. 两两交换链表中的节点

    方法1:

    class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode dummyHead = new ListNode(-1);
            dummyHead.next = head;
            ListNode pre = dummyHead;
            ListNode p1 = null, p2 = null;
            while (pre.next != null && pre.next.next != null) {
                p1 = pre.next;
                p2 = p1.next;
                // 调整指针
                p1.next = p2.next;
                p2.next = p1;
                pre.next = p2;
                // 更新指针
                pre = p1;  // 交换后 p1是较后面那个节点
            }
            return dummyHead.next;
        }
    }

    方法2:递归

      递归三部曲:1.找终止条件; 2.找返回值; 3.本级递归的任务。

      递归法要从宏观上考虑问题,此时链表只有三部分,head -> next -> 已处理好的部分

      因此,递归的任务就是要交换前两个节点。

    class Solution {
        public ListNode swapPairs(ListNode head) {
            // 终止条件
            if (head == null || head.next == null) return head;
            // 一共三个节点:head, next, swapPairs(next.next)
            ListNode next = head.next;
            head.next = swapPairs(next.next);
            next.next = head;
            // 根据第二步:返回给上一级的是当前已经完成交换后,即处理好了的链表部分
            return next;
        }
    }
  • 相关阅读:
    POJ3040--Allowance(贪心)
    Deep work
    湾区公司上班第一周
    三个现场面试
    协商薪资
    调节情绪,精神愉悦,健康快乐
    Phone interview guide 多说
    Campus Bikes
    降低软件复杂度 和 写注释写总结 2019-10
    某厂在线测试 2019.09.26
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/14133677.html
Copyright © 2011-2022 走看看