一、單鏈表倒序node
定義鏈表節點Node算法
public class Node { private int index; public Node next; public Node(NodeBuilder builder) { this.index = builder.getIndex(); this.next = builder.getNext(); } public static NodeBuilder newBuilder() { return new NodeBuilder(); } }
Node建造器ui
public class NodeBuilder { private int index; private Node next; public int getIndex() { return index; } public NodeBuilder setIndex(int index) { this.index = index; return this; } public Node getNext() { return next; } public NodeBuilder setNext(Node next) { this.next = next; return this; } public Node builder(){ return new Node(this); } }
反轉鏈表節點算法this
public class ReverseLinkedlist { /** * 反轉單鏈表 1->2->3->4->null 轉成 4->3->2->1->null * * @param node * @return */ static Node reverse(Node node) { // 當前節點的前一個節點 Node pre = null; // 保存剩下的鏈表 Node next = null; while (node != null) { next = node.next; node.next = pre; // 第一次將1->null,接着2->1->null,3->2->1->null,4->3->2->1->null pre = node; node = next; } return pre; } public static void main(String[] args) { Node node4 = Node.newBuilder().setNext(null).setIndex(4).builder(); Node node3 = Node.newBuilder().setNext(node4).setIndex(3).builder(); Node node2 = Node.newBuilder().setNext(node3).setIndex(2).builder(); Node node = Node.newBuilder().setNext(node2).setIndex(1).builder(); Node newNode = reverse(node); } }
二、二叉樹遍歷spa
public class TreeTraversal { /** * 前序遍歷,根左右 */ public static void preTraversalTree(TreeNode node) { if (node == null) { return; } System.out.println(node.data); preTraversalTree(node.leftChild);// 左子節點不斷入棧,直到沒有左子節點,再挨個輸出結果 preTraversalTree(node.rightChild); } /** * 中序遍歷,左根右 * @param node */ public static void midTraversalTree(TreeNode node) { if (node == null) { return; } midTraversalTree(node.leftChild); System.out.println(node.data); midTraversalTree(node.rightChild); } /** * 後序遍歷,左右根 * @param node */ public static void finTraversalTree(TreeNode node) { if (node == null) { return; } finTraversalTree(node.leftChild); finTraversalTree(node.rightChild); System.out.println(node.data); } /** * 樹節點 */ static class TreeNode { int data; TreeNode leftChild; TreeNode rightChild; } }
其實遞歸的雙次調用就是等前一個所有入棧後,每一次出棧,再調用後一個入棧。code