標籤:node 程式 練習 his mat next ext lock 複習
棧(stack)可以看做是特殊類型的線性表,訪問、插入和刪除其中的元素只能在棧尾(棧頂)進行。
隊列(queue)表示一個等待的線性表,它也可以看做是一種特殊類型的線性表,元素只能從隊列的末端(隊列尾)插入,從開始(隊列頭)訪問和刪除。
————Java語言程式設計 進階篇(原書第8版)
棧是先進後出(LIFO),而隊列是先進先出(FIFO)。
實現棧這個資料結構的代碼
package struct;//late in first out,LIFOpublic class MyStack<E>{ private Node<E> head = null; public MyStack(){} public MyStack(E element) { Node<E> newNode = new Node<E>(element); head = newNode; } private class Node<E> { E element; Node<E> next; public Node(E element) { this.element = element; } } //pop out a element public E pop() { Node<E> popOut = head; head=head.next; return popOut.element; } //push a new element into stack public void push(E element) { Node<E> newNode = new Node<E>(element); if(head!=null) { newNode.next=head; head=newNode; } else { head=newNode; } } //show the first element public E peek() { return head.element; } //empty or not public boolean empty() { if(head!=null) return false; else return true; } public static void main(String[] args) { //about String MyStack<String> stack1 = new MyStack<String>(); stack1.push("sss"); stack1.push("dddd"); stack1.push("dsds"); System.out.println("begin"); while(stack1.empty()==false) { System.out.print(stack1.pop()+" "); } System.out.println(); System.out.println("end"); //about Integer MyStack<Integer> stack2 = new MyStack<Integer>(); stack2.push(212); stack2.push(545); stack2.push(54643); stack2.push(000); System.out.println("begin"); while(stack2.empty()==false) { System.out.print(stack2.pop()+" "); } System.out.println(); System.out.println("end"); //no matter of the type MyStack stack3 = new MyStack(); stack3.push(212); stack3.push("sdad"); stack3.push(54643.787f); stack3.push(0.98989); System.out.println("begin"); while(stack3.empty()==false) { System.out.print(stack3.pop()+" "); } System.out.println(); System.out.println("end"); //LIFO MyStack<String> stack4 = new MyStack<String>("first"); stack4.push("second"); stack4.push("third"); stack4.push("forth"); System.out.println("begin"); while(stack4.empty()==false) { System.out.print(stack4.pop()+" "); } System.out.println(); System.out.println("end"); } }
在寫這個資料結構的過程中,也稍微複習了一下泛型。然後注意到,其實泛型型別是不能用基本類型的,至少要用基本類型的相應封裝類。
泛型型別必須是參考型別。不能用像int、double或char這樣的基本類型來替換泛型型別。而應該使用對應的Integer、Double或Character來代替。
————Java語言程式設計 進階篇(原書第8版)
Java-資料結構練習