基於連結串列的佇列實現
阿新 • • 發佈:2018-12-27
1.建立鏈節點類link
只有一種資料int型別,和對下一個鏈節點的引用next
public class Link {
public int a;
public Link next;
public Link(int m){
a=m;
}
public void displayLink(){
System.out.print(a +" ");
}
}
2.建立雙端連結串列FirstLastList
public class FirstLastList { private Link first; private Link last; public void FirstLastList(){ first=null; last=null; } public boolean isEmpty(){ return (first==null); } public void insertLast(int a){ //連結串列尾部插入資料 Link newLink =new Link(a); if (isEmpty()){ first=newLink; }else { last.next=newLink; } last=newLink; } public int deleteFirst(){ //預設非空 //連結串列頭部刪除資料 int temp=first.a; if (first.next==null){ last=null; } first=first.next; return temp; } public void displayLinklist(){ //顯示 Link current=first; System.out.println("連結串列資料為:"); while (current!=null){ current.displayLink(); current=current.next; } System.out.println(" "); } }
3.建立LinkQueue類對FirstLastList中的方法進行封裝
public class LinkQueue { private FirstLastList theList; public LinkQueue(){ theList=new FirstLastList(); } public void insert (int a){ //入隊 theList.insertLast(a); } public int deleteFirst(){ //出隊 return theList.deleteFirst(); } public boolean isEmpty(){ return (theList.isEmpty()); } public void display(){ System.out.print("隊頭--->>隊尾的"); theList.displayLinklist(); } }
**4.測試類LinkQueueApp **
public class LinkQueueApp {
public static void main(String args[]){
LinkQueue l=new LinkQueue();
l.insert(5);
l.insert(4);
l.insert(3);
l.display();
l.deleteFirst();
l.display();
}
}
測試結果: