zoukankan      html  css  js  c++  java
  • 24. Swap Nodes in Pairs 链表每2个点翻转一次

    [抄题]:

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

    Example:

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

    Note:

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

     [暴力解法]:

    时间分析:

    空间分析:dummy node,新建才是n,不新建就是1

     [优化后]:

    时间分析:

    空间分析:recursive用的是stack, 空间恒定为n.

    特例:尾递归是1

    [奇葩输出条件]:

    [奇葩corner case]:

    从节点非空就行了

    [思维问题]:

    不知道指针用什么顺序交换:

    先外后里,外面的两点前后无所谓。

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [一句话思路]:

    用一个cur做主节点 负责移动,一个first second分别做后面两个从节点(因此循环条件就是从节点非空?)

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 不知道指针的改变是按什么顺序的:先外面、后里面
    2. 不知道指针的改变怎么写:就和方程左边指向方程右边即可

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    学了很多:先外后里,左指右,从节点非空

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode swapPairs(ListNode head) {
            //cc
            if (head == null) return head; 
            
            //ini: dummy node
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode cur = dummy;
            
            //while loop if the two nodes are not null
            while (cur.next != null && cur.next.next != null) {
                //initialize two ListNode
                ListNode first = cur.next;
                ListNode second = cur.next.next;
                
                //change the pointer
                cur.next = second;
                first.next = second.next;
                second.next = first;
                
                //move the cur
                cur = cur.next.next;
            }
        
            return dummy.next;
        }
    }
    View Code
  • 相关阅读:
    学算法还能指导找对象?是的,这就是大名鼎鼎的稳定婚姻算法
    机器学习 | 详解GBDT梯度提升树原理,看完再也不怕面试了
    Python | 面试的常客,经典的生产消费者模式
    LeetCode 89,因为题目晦涩而被点了1500+反对的搜索问题
    LeetCode 87,远看是字符串其实是搜索,你能做出来吗?
    Golang | Go语言多态的实现与interface使用
    pandas | DataFrame基础运算以及空值填充
    算法数据结构 | 只要30行代码,实现快速匹配字符串的KMP算法
    Mac上使用Docker安装SQLServer
    [翻译]ASP.NET Core在 .NET 5 Preview 7的更新
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9397580.html
Copyright © 2011-2022 走看看