標籤:log clear nod private tac ack builder 元素 creat
棧:後進先出 LIFO
生活執行個體:先進電梯後出來
儲存元素的基本結構:
public class Node { /* 元素有兩部分: 元素的值 下一個元素的引用 */ Object data;//資料域 Node next; //指標域 public Node(){} public Node(Object data,Node next){ this.data=data; this.next=next; }}
實現棧:
/** * Created by yaming * 棧的鏈式儲存 */public class LinkStack{ private Node top;//棧頂元素 private int size;//當前棧大小 public LinkStack(){ top=null; } /** * 當前棧的大小 * @return */ public int length() { return size; } /** * 判斷棧是否為空白 * @return */ public boolean isEmpty() { return size==0?true:false; } /** * 入棧 * @param data * @return */ public boolean push(Object data){ Node node=new Node(data,null); if(isEmpty()){ top=node; }else { node.next=top;//把元素放在棧頂,引用指向棧頂 top=node; } size++;//元素入棧,棧頂上升 return true; } /** * 出棧 * @return */ public Object pop(){ if(isEmpty()){ return null; }else { Node value=top;//得到棧頂元素 top=top.next;//更新前端節點 value.next=null;//棧頂元素的引用設定為null,該元素被回收 size--; return value.data; //出棧的元素 } } /** * 返回棧頂元素 * @return */ public Object peek(){ if(isEmpty()){ return null; } return top.data; } /** * 遍曆棧 * @return */ public String stack(){ if(isEmpty()){ return "[]"; }else { StringBuilder stringBuilder=new StringBuilder("["); for (Node current=top;current!=null;current=current.next){ stringBuilder.append(current.data.toString()+", "); } int length=stringBuilder.length(); return stringBuilder.delete(length-2,length).append("]").toString(); } } public void clear(){ top=null; size=0; }}
棧--java實現