1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| class FirstLastList_long{ private Link_long first; private Link_long last; public FirstLastList_long() { //构造函数 this.first = null; this.last = null; } public boolean isEmpty(){ return (first == null); } public void insertFirst(long dd){ //从链表的头开始插入 Link_long newLink = new Link_long(dd); if(isEmpty()){ last = newLink; //不用改变first } newLink.next = first; first = newLink; } public void insertLast(long dd){ //从链表的尾开始插入 Link_long newLink = new Link_long(dd); if(isEmpty()){ first = newLink; //不用改变last }else{ last.next = newLink; //在last后面添加新元素,并修改last的位置 } last = newLink; //注意:只有一个元素的时候,插入要把last也赋为newLink } public long deleteFirst(){ Link_long temp = first; //暂存first if(first.next == null){ //如果只有一个元素,把last也赋为null last = null; } first = first.next; //把next设为first return temp.dData; //返回原来的first } public void displayList(){ System.out.println("List(first-->last):"); Link_long current = first; //用于不断改变位置实现遍历 while(current != null){ current.displayLink(); current = current.next; } } }
class LinkQueue{ private FirstLastList_long theList;
public LinkQueue() { //构造函数 theList = new FirstLastList_long(); //创建一个双端链表对象 } public void push(long j){ //从链表的尾开始插入,新来的元素在尾部 theList.insertLast(j); } public long pop(){ return theList.deleteFirst(); //从链表的头开始弹出,先进的元素先被弹出 } public boolean idEmpty(){ return theList.isEmpty(); } public void displayQueue(){ System.out.println("Queue (front-->rear)"); theList.displayList(); } }
public class LinkQueue_demo {
public static void main(String[] args) { // TODO 自动生成的方法存根 LinkQueue theQueue = new LinkQueue(); theQueue.push(10); theQueue.push(20); theQueue.push(30); theQueue.displayQueue(); theQueue.pop(); theQueue.pop(); theQueue.displayQueue(); }
}
|