1. 栈概念
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈 顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。 出栈:栈的删除操作叫做出栈。出数据在栈顶。
2.使用顺序表来实现栈结构
public class creatStack {
//暂时不考虑扩容问题
int []array=new int[100];
int size=0;
public void push(int value){
array[size++]=value;
}
public int pop(){
return array[--size];
}
public int peek() {
return array[size - 1];
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
}
3.队列的概念
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾(Tail/Rear) 出队列:进行删除操作的一端称为队头 (Head/Front)
4.队列的实现
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上 出数据,效率会比较低。
实现代码:
public class creatQueue {
private Node head = null;
private Node tail = null;
private int size = 0;
public void offer(int v) {
Node node = new Node(v);
if (tail == null) {
head = node;
} else {
tail.next = node;
}
tail = node;
size++;
}
public int poll() {
if (size == 0) {
throw new RuntimeException("队列为空");
}
Node oldHead = head;
head = head.next;
if (head == null) {
tail = null;
}
size--;
return oldHead.val;
}
public int peek() {
if (size == 0) {
throw new RuntimeException("队列为空");
}
return head.val;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
}
class Node {
int val;
Node next;
Node(int val, Node next) {
this.val = val;
this.next = next;
}
Node(int val) {
this(val, null);
}
}
5.双端队列(deque)的概念
双端队列(deque)是指允许两端都可以进行入队和出队操作的队列,deque 是 “double ended queue” 的简称。 那就说明元素可以从队头出队和入队,也可以从队尾出队和入队。
6.练习题
6.1 括号匹配问题
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效
public class Num20 {
public boolean isValid(String s) {
Stack<Character> stack=new Stack();
for (int i=0;i<s.length();i++){
if (s.charAt(i)=='('){
stack.push(')');
}else if (s.charAt(i)=='{'){
stack.push('}');
}else if (s.charAt(i)=='['){
stack.push(']');
}else if (stack.isEmpty()||s.charAt(i)==stack.pop()){
return false;
}
}
return stack.isEmpty();
}
}
6.2 使用两个队列来实现栈
public class Num225 {
Queue<Integer> a;
Queue <Integer>b;
public Num225() {
a=new LinkedList<Integer>();
b=new LinkedList<Integer>();
}
public void push(int x) {
a.offer(x);
}
public int pop() {
while (a.size()>1) {
b.offer(a.poll());
}
int as=a.poll();
while (b.size()>1) {
a.offer(b.poll());
}
return as;
}
public int top() {
while (a.size()>1) {
b.offer(a.poll());
}int as=a.peek();
while (b.size()>1) {
a.offer(b.poll());
}
return as;
}
6.3用两个栈来实现队列
package Revirw.Stack;
import java.util.Stack;
class MyQueue {
private Stack<Integer> a;// 输入栈
private Stack<Integer> b;// 输出栈
public MyQueue() {
a = new Stack<>();
b = new Stack<>();
}
public void push(int x) {
a.push(x);
}
public int pop() {
// 如果b栈为空,则将a栈全部弹出并压入b栈中,然后b.pop()
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.pop();
}
public int peek() {
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.peek();
}
public boolean empty() {
return a.isEmpty() && b.isEmpty();
}
}