鏈表棧與鏈表隊列
鏈表實現的棧和隊列,這裏只展示實現過程,有不明的地方可以參看我的前面關於棧,隊列和列表的說明
//棧:先進後出 class LinkStack{ public static void main(String[] args) { LinkStack l = new LinkStack(); l.push(1); l.push(2); l.push(3); l.displayStack(); l.pop(); l.displayStack(); } public Link first; public LinkStack(){ first = null; } public void push(int i){ Link newLink = new Link(i); newLink.next = first; first = newLink; } public void pop(){ if(isEmpty()){ System.out.println("Stack is empty"); } first = first.next; } public void displayStack(){ if(isEmpty()){ System.out.println("Stack is empty"); }else{ Link current = first; while(current != null){ current.displayLink(); current = current.next; } } } public boolean isEmpty(){ return first == null; } } //鏈接點對象 class Link{ public int iData; //關係子段,用於存儲下一個鏈接點的位置 public Link next; public Link(int id){ this.iData = id; } public void displayLink(){ System.out.println("{" + iData + "}"); } }
//隊列:先進先出 class LinkQueue { public static void main(String[] args) { LinkQueue lq = new LinkQueue(); lq.insert(1); lq.insert(2); lq.disPlay(); lq.remove(); System.out.println("remove----"); lq.disPlay(); } public Link first; public Link last; public LinkQueue() { first = null; last = null; } public boolean isEmpty() { return first == null; } public void insert(int value) { Link newLink = new Link(value); if (isEmpty()) { first = newLink; } else { last.next = newLink; } last = newLink; } public void remove() { if (isEmpty()) { System.out.println("LinkQueue is empty"); } else { if (first.next == null) { last = null; } first = first.next; } } public void disPlay(){ Link current = first; while(current!=null){ current.displayLink(); current = current.next; } } } // 鏈接點對象 class Link { public int iData; // 關係子段,用於存儲下一個鏈接點的位置 public Link next; public Link(int id) { this.iData = id; } public void displayLink() { System.out.println("{" + iData + "}"); } }