链表栈与链表队列
链表实现的栈和队列,这里只展示实现过程,有不明的地方可以参看我的前面关于栈,队列和列表的说明
//栈:先进后出 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 + "}"); } }