隊列和堆棧是數據結構中的兩種基本數據類型。Java語言可以使用數組和鏈表來構建隊列和堆棧。
隊列是一種先進先出(FIFO)的數據結構,它的實現可以使用鏈表和數組。下面是使用數組實現隊列的Java代碼:
public class MyQueue { private int maxSize; private int[] queueArray; private int front; private int rear; private int items; public MyQueue(int s) { maxSize = s; queueArray = new int[maxSize]; front = 0; rear = -1; items = 0; } public void insert(int j) { if(rear == maxSize-1) rear = -1; queueArray[++rear] = j; items++; } public int remove() { int temp = queueArray[front++]; if(front == maxSize) front = 0; items--; return temp; } public int peek() { return queueArray[front]; } public boolean isEmpty() { return (items == 0); } public boolean isFull() { return (items == maxSize); } public int size() { return items; } }
堆棧是一種后進先出(LIFO)的數據結構,它的實現也可以使用鏈表和數組。下面是使用鏈表實現堆棧的Java代碼:
public class MyStack { private LinkedListstackList; public MyStack() { stackList = new LinkedList (); } public void push(int j) { stackList.addFirst(j); } public int pop() { return stackList.removeFirst(); } public int peek() { return stackList.getFirst(); } public boolean isEmpty() { return stackList.isEmpty(); } public int size() { return stackList.size(); } }
上一篇css下拉菜單案例