用JAVA語言,編寫一個鏈表類(雙向鏈表),實現插入,刪除,尋找操作__JAVA

來源:互聯網
上載者:User
定義介面://Deque.javapackage dsa;     //根據自己的程式位置不同public interface Deque {public int getSize();//返回隊列中元素數目public boolean isEmpty();//判斷隊列是否為空白public Object first() throws ExceptionQueueEmpty;//取首元素(但不刪除)public Object last() throws ExceptionQueueEmpty;//取末元素(但不刪除)public void insertFirst(Object obj);//將新元素作為首元素插入public void insertLast(Object obj);//將新元素作為末元素插入public Object removeFirst() throws ExceptionQueueEmpty;//刪除首元素public Object removeLast() throws ExceptionQueueEmpty;//刪除末元素public void Traversal();//遍曆}雙向鏈表實現://Deque_DLNode.java/* * 基於雙向鏈表實現雙端隊列結構 */package dsa;public class Deque_DLNode implements Deque {protected DLNode header;//指向前端節點(哨兵)protected DLNode trailer;//指向尾節點(哨兵)protected int size;//隊列中元素的數目//建構函式public Deque_DLNode() {header = new DLNode();trailer = new DLNode();header.setNext(trailer);trailer.setPrev(header);size = 0;}//返回隊列中元素數目public int getSize(){ return size; }//判斷隊列是否為空白public boolean isEmpty(){ return (0 == size) ? true : false; }//取首元素(但不刪除)public Object first() throws ExceptionQueueEmpty {if (isEmpty())throw new ExceptionQueueEmpty("意外:雙端隊列為空白");return header.getNext().getElem();}//取末元素(但不刪除)public Object last() throws ExceptionQueueEmpty {if (isEmpty())throw new ExceptionQueueEmpty("意外:雙端隊列為空白");return trailer.getPrev().getElem();}//在隊列前端插入新節點public void insertFirst(Object obj) {DLNodesecond = header.getNext();DLNodefirst = new DLNode(obj, header, second);second.setPrev(first);header.setNext(first);size++; }//在隊列後端插入新節點public void insertLast(Object obj) {DLNodesecond = trailer.getPrev();DLNodefirst = new DLNode(obj, second, trailer);second.setNext(first);trailer.setPrev(first);size++; }//刪除首節點public Object removeFirst() throws ExceptionQueueEmpty {if (isEmpty())throw new ExceptionQueueEmpty("意外:雙端隊列為空白");DLNodefirst = header.getNext();DLNodesecond = first.getNext();Objectobj = first.getElem();header.setNext(second);second.setPrev(header);size--;return(obj);}//刪除末節點public Object removeLast() throws ExceptionQueueEmpty {if (isEmpty())throw new ExceptionQueueEmpty("意外:雙端隊列為空白");DLNodefirst = trailer.getPrev();DLNodesecond = first.getPrev();Objectobj = first.getElem();trailer.setPrev(second);second.setNext(trailer);size--;return(obj);}//遍曆public void Traversal() {DLNodep = header.getNext();while (p != trailer) {System.out.print(p.getElem()+" ");p = p.getNext();}System.out.println();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.