LinkedList(實現了queue,deque接口,List接口)實現棧和隊列的功能


 LinkedList是用雙向鏈表結構存儲數據的,很適合數據的動態插入和刪除,隨機訪問和遍歷速度比較慢。

底層是一個雙向鏈表,鏈表擅長插入和刪除操作,隊列和棧最常用的2種操作都設計到插入和刪除








import java.util.LinkedList;
import java.util.Queue;
//用linkedList模擬隊列,因為鏈表擅長插入和刪除
public class Hi {
    public static void main(String [] args) { //做劍指offer遇見過這個數結
        Queue<String> queue = new LinkedList<String>();
        //追加元素
        queue.add("zero");
        queue.offer("one");
        queue.offer("two");
        queue.offer("three");
        queue.offer("four");
        System.out.println(queue);//[zero, one, two, three, four]
        //從隊首取出元素並刪除
        System.out.println(queue.poll());// zero
        System.out.println(queue.remove());//one
        System.out.println(queue);//[two, three, four]
        //從隊首取出元素但是不刪除
        String peek = queue.peek();
        System.out.println(peek); //two
        //遍歷隊列,這里要注意,每次取完元素后都會刪除,整個
        //隊列會變短,所以只需要判斷隊列的大小即可
        while(queue.size() > 0) {
            System.out.println(queue.poll());
        }//two three four
    }
}

  




 

 //用linkedList模擬棧,因為鏈表擅長插入和刪除

import java.util.Deque;
import java.util.LinkedList;

public class Hi {
    public static void main(String[] args) {
        /*模擬棧,這是從頭開始進來的*/
    	Deque<String> deque = new LinkedList<String>();
        /*Pushes an element onto the stack 
         *at the head of this dequeue */
        deque.push("a");
        deque.push("b");
        deque.push("c");
        System.out.println(deque); //[c, b, a] 
        //獲取棧首元素后,元素不會出棧
        System.out.println(deque.peek());//c
        while(deque.size() > 0) {
            //獲取棧首元素后,元素將會出棧
            System.out.println(deque.pop());//c b a
        }
        System.out.println(deque);//[]
        
        /*模擬棧*/
        deque.offerLast("a");
        deque.offerLast("b");
        deque.offerLast("c");// [a, b, c]
        while(!deque.isEmpty())
        	System.out.println(deque.pollLast());
    }   // 先輸出c再b最后a
}

  





import java.util.Stack;
//沒有用到接口編程
public class Hi {
    public static void main(String[] args) {
      Stack<Integer> s = new Stack<Integer>();
      s.push(1);
      s.push(2);// [1,2]
      s.push(3);// [1,2,3]
      while(!s.isEmpty()){
    	  System.out.println(s.pop());
      }//依次輸入 3 接着是2 ,然后1
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM