java 단일 체인 테이블 역전 실현


class Node {
    Node next;
    String name;
    public Node(String name) {
        this.name = name;
    }

    /**
     *     
     */
    public void show() {
        Node temp = this;
        do {
            System.out.print(temp + "->");
            temp = temp.next;
        }while(temp != null);
        System.out.println();
    }

    /**
     *          ,  :     ,   StackOverflowError
     * @param n
     * @return
     */
    public static Node recursionReverse(Node n) {
        long start = System.currentTimeMillis();
        if(n == null || n.next == null) {
            return n;
        }
        Node reverseNode = recursionReverse(n.next);

        n.next.next = n;
        n.next = null;
        System.out.println("      :" + (System.currentTimeMillis() - start) + "ms...");
        return reverseNode;
    }

    /**
     *          
     * @param n
     * @return
     */
    public static Node loopReverse(Node n) {
        long start = System.currentTimeMillis();
        if(n == null || n.next == null) {
            return n;
        }

        Node pre = n;
        Node cur = n.next;
        Node next = null;
        while(cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        n.next = null;
        n = pre;
        System.out.println("      :" + (System.currentTimeMillis() - start) + "ms...");
        return pre;
    }

    @Override
    public String toString() {
        return name;
    }
  
  public static void main(String[] args) {

        int len = 10;
        Node[] nodes = new Node[len];
        for(int i = 0; i < len; i++) {
            nodes[i] = new Node(i + "");
        }
        for(int i = 0; i < len - 1; i++) {
            nodes[i].next = nodes[i+1];
        }
       /* try {
            Thread.sleep(120000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        Node r1 = Node.loopReverse(nodes[0]);
        r1.show();
        Node r = Node.recursionReverse(r1);
        r.show();

    } 
}

인용하다
총결산
인용하다
귀환과 순환에 대해 순환 실현을 추천합니다. 귀환은 단일 체인표가 너무 크면 나타날 수 있습니다.
StatckOverflowError, 반복은 메소드 호출과 관련되며, 성능에서도 루프 구현보다 약합니다.

좋은 웹페이지 즐겨찾기