数据结构-栈
栈
先入先出的数据结构(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 = 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());
}
}
}
浙公网安备 33010602011771号