zoukankan      html  css  js  c++  java
  • 题型总结之Linked List

    何时用dummy

    给定链表的head结点可能最先被删除/移动? Yes-> 无脑用dummy

            ListNode dummy = new ListNode(-1);
            ListNode pre = dummy;
            dummy.next = head;
    ...
    return dummy.next;

      

    反转链表

    public ListNode reverseList(ListNode head){
            ListNode pre = null;
            ListNode cur = head;
            while(cur!= null){
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;
            }
            return pre;
        }
    

    计算整个链表长度

      public int getLength(ListNode head){
            int len = 0;
            ListNode cur = head;
            while(cur != null){
                cur = cur.next;
                len++;
            }
            return len;
        }
    

    快慢指针

    • 找中点
    • 找离end of list距离为k的点
    • 找cycle
    • 找intersection
    ListNode slow = head; 
    ListNode fast = head;
    /**
     * Change this condition to fit specific problem.
     * Attention: remember to avoid null-pointer error
     **/
    
    while (fast != null && fast.next != null) {
        slow = slow.next;           // move slow pointer one step each time
        fast = fast.next.next;      // move fast pointer two steps each time
        if (slow == fast) {         // change this condition to fit specific problem
            return true;
        }
    }
    return false;   // change return value to fit specific problem
    

      

  • 相关阅读:
    mysql显示乱码
    aws常用命令
    Hive分析窗口函数(一) SUM,AVG,MIN,MAX
    Hive函数介绍
    Apache Drill 调研学习
    公有云与私有云对比分析报告
    python3 使用libvirt 相关安装
    libvirt虚拟库
    Reveal CocoaPods的使用
    AFNetworking 2.0 使用
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/14210795.html
Copyright © 2011-2022 走看看