上一篇文章中咱們聊到了棧——漫畫趣解什麼是棧?
相信不少小夥伴都理解了棧;
那麼此次,一樣採用漫畫形式,給你們聊一聊什麼是隊列;java
隊列是一種受限的線性表;
隊列只容許在一端進行插入操做,另外一端進行刪除操做;程序員
容許插入的一端叫隊尾,容許刪除的的一端叫隊頭;
即先進先出,後進後出;數組
文中完整源碼獲取請關注公衆號《程序員的時光》;
後臺回覆——數據結構源碼,能夠得到常見數據結構代碼;數據結構
隊列的順序存儲:
方法類:ide
//入隊 public void Push_SeqQueue(SeqQueue queue, Object data){ if(queue==null){ return; } if(data==null){ return; } //若是隊列容量小於或等於數組容量 if(queue.size==Max_Size){ return; } //元素入隊 queue.data[queue.size]=data; queue.size++; } //返回隊頭元素 public Object Front_SeqQueue(SeqQueue queue){ if(queue==null){ return null; } if(queue.size==0){ return null; } //隊頭元素下標爲0 return queue.data[0]; } //出隊 public void Pop_SeqQueue(SeqQueue queue){ if(queue==null){ return; } if(queue.size==0){ return; } //出隊操做須要移動所有元素 for (int i = 0; i < queue.size-1; i++) { queue.data[i]=queue.data[i+1]; } queue.size--; }
主函數:函數
public static void main(String[] args) { SeqQueueDao seqQueueDao=new SeqQueueDao(); //初始化隊列 SeqQueue queue=seqQueueDao.Init_SeqQueue(); //入隊 seqQueueDao.Push_SeqQueue(queue,"A"); seqQueueDao.Push_SeqQueue(queue,"B"); seqQueueDao.Push_SeqQueue(queue,"C"); seqQueueDao.Push_SeqQueue(queue,"D"); seqQueueDao.Push_SeqQueue(queue,"E"); //出隊 while (queue.size>0){ //查找隊頭元素 Object o=seqQueueDao.Front_SeqQueue(queue); System.out.println(o); //出隊 seqQueueDao.Pop_SeqQueue(queue); } }
運行結果:
隊列的鏈式存儲:
方法類:spa
//入隊列 public void Push_LinkQueue(LinkQueue queue,Object data){ if (queue == null){ return; } if (data == null){ return; } //建立新插入的結點,也就是隊列頂指針後面的第一個元素,由於只能在隊列頂進行元素插入或刪除 LinkQueueNode newNode=new LinkQueueNode(data,null); //進入插入操做 newNode.next=queue.head.next; //隊列頂指針的next等於新插入結點 queue.head.next=newNode; //隊列容量加1 queue.size++; } //出隊列 public void Pop_LinkQueue(LinkQueue queue){ if (queue == null){ return; } if (queue.size == 0){ return; } //pPrev指頭結點,pCurrent指頭結點後面的第一個元素,直到pCurrent爲空爲止 LinkQueueNode pPrev=queue.head; LinkQueueNode pCurrent=pPrev.next; while (pCurrent.next!=null){ pPrev=pCurrent; pCurrent=pPrev.next; } pPrev.next=null; //隊列容量減1 queue.size--; } //返回隊頭元素 public Object Front_LinkQueue(LinkQueue queue){ if (queue == null){ return null; } if (queue.size == 0){ return null; } //隊頭元素也就是前面插入的元素,採用循環一直找到隊頭元素 LinkQueueNode pCurrent=queue.head; while (pCurrent.next!=null){ pCurrent=pCurrent.next; } return pCurrent.data; }
主函數:3d
public static void main(String[] args) { LinkQueueDao linkQueueDao=new LinkQueueDao(); //初始化隊列 LinkQueue queue=linkQueueDao.Init_LinkQueue(); //入隊列 linkQueueDao.Push_LinkQueue(queue,"A"); linkQueueDao.Push_LinkQueue(queue,"B"); linkQueueDao.Push_LinkQueue(queue,"C"); linkQueueDao.Push_LinkQueue(queue,"D"); linkQueueDao.Push_LinkQueue(queue,"E"); //輸出隊列元素 while(!linkQueueDao.IsEmpty_LinkQueue(queue)){ //查找隊頭元素 Object o=linkQueueDao.Front_LinkQueue(queue); System.out.println(o); //出隊列 linkQueueDao.Pop_LinkQueue(queue); } }
運行結果:
好了,今天就先分享到這裏了,下期給你們帶來樹的講解!指針
**原創實屬不易,求個關注吧~**