zoukankan      html  css  js  c++  java
  • problem report: middle of linked list

     Middle of Linked List

    propose: get the middle element of a linked list

    method: 1. use two pointers 

    conplexity: o(n)

    example:

    Given 1->2->3, return the node with value 2.

    Given 1->2, return the node with value 1.

    mycode:

            ListNode firstPointer = new ListNode(0);
            ListNode secondPointer = new ListNode(0);
            if (head == null) {
                return null;
            }
            firstPointer = head;
            secondPointer = head.next;
            
            if (secondPointer == null || secondPointer.next == null) {
                return firstPointer;
            }
     if (head == null || head.next == null) {
                return head;
            }
            
            ListNode slow = head, fast = head.next;

    reflections: 1. the third element euqal to null, do not need to consider as an special case! The two return statement of if actually do the same things. Use head to represend the return value. Use two different pointers as return value looks massy. (Reconsider the special case, tell whether there is an easy way to represent,especially for several if statement)

          2. it's more reasonalbe to name the two pointer slow and fast

          3. differece of stack and heap variable

    iterative body part:

     mycode:

    while( secondPointer.next != null && secondPointer.next.next != null) {
                secondPointer = secondPointer.next.next;
                firstPointer = firstPointer.next;
            }
            
            if (secondPointer.next != null) {
                firstPointer = firstPointer.next;
            }
            return firstPointer;

    answers:

    1  while (fast != null && fast.next != null) {
    2             slow = slow.next;
    3             fast = fast.next.next;
    4         }
    5         
    6         return slow;

    refelection: consider null element in the end of linked list as an normal node. Test fast and fast.next in the while loop can simplify the code.

  • 相关阅读:
    NoHttp开源Android网络框架1.0.0之架构分析
    3种浏览器性能測试
    自己定义控件-画板,橡皮擦,刮刮乐
    android优化 清除无效代码 UCDetector
    iOS推送 (百度推送)
    C#中的协变OUT和逆变
    使用反射构造对象实例并动态调用方法
    用反射获取构造函数带参数的实例对象
    自己实现一个IOC(控制翻转,DI依赖注入)容器
    func 和action 委托的使用
  • 原文地址:https://www.cnblogs.com/jiangchen/p/5529704.html
Copyright © 2011-2022 走看看