欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

java構建隊列和堆棧

陳思宇1年前7瀏覽0評論

隊列和堆棧是數據結構中的兩種基本數據類型。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();
}
}