堆疊
先入先出的資料結構(LIFO)
在LIFO資料結構中,將首先處理添加到佇列中的最新元素,
與佇列不同,堆疊是一個LIFO資料結構,通常,插入操作在堆疊中被稱為入堆疊push,與佇列類似,總是在堆疊的末尾添加一個新的元素,但是洗掉操作,退堆疊pop,將始終洗掉佇列中相對于它的最后一個元素,
入堆疊

出堆疊

堆疊的順序存盤結構
// "static void main" must be defined in a public class.
class MyStack {
private List<Integer> data; // store elements
public MyStack() {
data = https://www.cnblogs.com/chuxb/p/new ArrayList<>();
}
/** Insert an element into the stack. */
public void push(int x) {
data.add(x);
}
/** Checks whether the queue is empty or not. */
public boolean isEmpty() {
return data.isEmpty();
}
/** Get the top item from the queue. */
public int top() {
return data.get(data.size() - 1);
}
/** Delete an element from the queue. Return true if the operation is successful. */
public boolean pop() {
if (isEmpty()) {
return false;
}
data.remove(data.size() - 1);
return true;
}
};
public class Main {
public static void main(String[] args) {
MyStack s = new MyStack();
s.push(1);
s.push(2);
s.push(3);
for (int i = 0; i < 4; ++i) {
if (!s.isEmpty()) {
System.out.println(s.top());
}
System.out.println(s.pop());
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/147642.html
標籤:Java
