it2024-12-09  22

栈和队列是有操作限制的线性表。 栈是一种只允许在一端进行插入或删除的线性表。

1、栈的操作端通常被称为栈顶,另一端被称为栈底。 2、栈的插入操作称为进栈(压栈|push);栈删除操作称为出栈(弹栈|pop)。

顺序存储的栈称为顺序栈;链式存储的栈称为链式栈。

我们可以围绕栈的4个元素来实现栈:

2状态:是否栈空;是否栈满。

2操作:压栈push;进栈pop。

顺序栈的实现

package test;

import org.junit.Test;

public class test {

@Test public void fun(){ //初始化栈(char类型) SqStack<Character> stack = new SqStack<Character>(10); //2状态 System.out.println("栈是否为空:"+stack.isNull()); System.out.println("栈是否已满:"+stack.isFull()); //2操作 //依次压栈 stack.push('a'); stack.push('b'); stack.push('c'); //依次弹栈 System.out.println("弹栈顺序:"); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); }

}

链式栈的实现

package test;

import org.junit.Test;

public class test {

@Test public void fun(){ LinkStack<Character> ls = new LinkStack<Character>(); //1状态 System.out.println("栈是否为空:"+ls.isNull()); //2操作 //依次压栈 ls.push(new LinkNode<Character>('a')); ls.push(new LinkNode<Character>('b')); ls.push(new LinkNode<Character>('c')); //依次弹栈 System.out.println("弹栈顺序:"); System.out.println(ls.pop().getData()); System.out.println(ls.pop().getData()); System.out.println(ls.pop().getData()); }

}

校验括号是否匹配

package test; import org.junit.Test; public class test { @Test public void fun(){ String str1 = "i((l)o[v{e}]y)o{u}!";//表达式1:(()[{}]){} String str2 = "you((do)[not{}])know{}!)";//表达式2:(()[{}]){}) boolean match1 = StackUtils.isMatch(str1); boolean match2 = StackUtils.isMatch(str2); System.out.println("str1中的括号是否匹配:"+match1); System.out.println("str2中的括号是否匹配:"+match2); } }

true false

最新回复(0)