Java 使用連結串列來實現佇列功能
阿新 • • 發佈:2019-02-05
/** * 連結串列元素定義 * Create by zxb on 2017/8/27 */ public class Element<T> { private Element<T> next; private T value; public Element<T> getNext() { return next; } public void setNext(Element<T> next) { this.next = next; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } } /** * 列表模板介面 * Created by zhengxb on 2017/8/27. */ public interface IList<T> { boolean pushBack(T newElement); boolean popFront(); Element<T> front(); int size(); } /** * 連結串列實現 * Create by zxb on 2017/8/27 */ public class ListImpl<T> implements IList<T> { private Element<T> first = null; private Element<T> last = null; private int size = 0; @Override public boolean pushBack(T newElement) { Element<T> element = new Element<>(); element.setValue(newElement); if (size == 0) { first = element; size++; return true; } if (last == null) { last = new Element<>(); last.setValue(newElement); first.setNext(last); } else { last.setNext(element); last = element; } size++; return true; } @Override public boolean popFront() { if (size == 0) { return false; } first = first.getNext(); size--; return true; } @Override public Element<T> front() { return first; } @Override public int size() { return size; } } /** * 佇列介面 * Create by zxb on 2017/8/27 */ public interface IQueue<R> { boolean push(R newElement); boolean pop(); R front(); int size(); boolean display(); } /** * 佇列實現 * Create by zxb on 2017/8/27 */ public class QueueImpl<R> implements IQueue<R> { private ListImpl<R> list; @Override public boolean push(R newElement) { if (list == null) { list = new ListImpl<>(); } list.pushBack(newElement); return true; } @Override public boolean pop() { if (list == null) { list = new ListImpl<>(); } list.popFront(); return true; } @Override public R front() { return list.front().getValue(); } @Override public int size() { return list.size(); } @Override public boolean display() { Element<R> front = list.front(); System.out.println("列表元素:"); Element<R> temp = front; while (temp != null) { System.out.print(temp.getValue()); temp = temp.getNext(); System.out.println("\t"); } return true; } } /** * Create by zxb on 2017/8/27 */ public class Test { public static void main(String[] args) { IQueue<String> queue = new QueueImpl<>(); queue.push("one"); queue.push("two"); queue.push("three"); queue.pop(); queue.display(); } }
執行結果: