數據結構算法回顧

今天發現本身對於數據結構有點陌生了,最近幾年主要精力放在語言層次上,這些基本的東西反而有些陌生了,溫故而知新,決定花些時間把這些東西整理下。本文不按期更新。

- 樹的層次遍歷node

輸入數據結構

4
      /   \
     6     9
    / \     \
   7   8     12

要求打印出 4->6->9->7->8->12this

public void PrintByLevel() {
        LinkedList<Tree> l = new LinkedList<Tree>();
        l.add(this);
        while (!l.isEmpty()) {
            Tree tmp = l.pollFirst();
            System.out.println(tmp.getValue());
            if (null != tmp.getLChild()) {
                l.add(tmp.getLChild());
            }
            if (null != tmp.getRChild()) {
                l.add(tmp.getRChild());
            }
        }
    }
  • 鏈表的遞歸和非遞歸反轉
    遞歸反轉

// 遞歸,在反轉當前節點以前先反轉後續節點code

public static ListNode Reverse(ListNode head) {
        if (null == head || null == head.next) {
            return head;
        }
        ListNode reversedHead = Reverse(head.next);
        head.next.next = head;
        head.next = null;
        return reversedHead;
    }

非遞歸反轉遞歸

public static ListNode NoneRecursiveReverse(ListNode head) {
    ListNode retval = null;
    ListNode node = head;
    ListNode preNode = null;
    while ( node != null ){
        // get the next node, and save it at pNext
        ListNode nextNode = node.next;
        // if the next node is null, the current is the end of original
        // list, and it's the head of the reversed list
        if ( nextNode == null) {
            retval = node;
        }
        // reverse the linkage between nodes
        node.next = preNode;
        preNode = node;
        node = nextNode;
    }
    return retval;
}
相關文章
相關標籤/搜索