栈
基本变量的变量和值还有数组和引用变量,对象的首地址都存于栈中,数组,引用变量和对象的内容都存在于堆中。
以下是JDK自带的STACK:
package com.zxc.stacklearning; import org.junit.Test; import java.util.Enumeration; import java.util.Stack; /** * Created by Administrator on 2018/2/15 0015. * JDK写的栈 */ public class MyStack { @Test public void test(){ Stack s=new Stack(); s.push(100); s.push(200); s.push("A"); s.push(100.1f); System.out.println(s.pop()); System.out.println(s.peek());//peek()用来查栈顶元素,不会弹出栈 System.out.println(s.empty()); System.out.println(s.isEmpty()); System.out.println(s.size()); Enumeration es=s.elements(); while(es.hasMoreElements()){ System.out.println(es.nextElement()); } } }
以下是自己手写的栈:
package com.zxc.stacklearning; import org.junit.Test; /** * Created by Administrator on 2018/2/15 0015. * 自己用Object[]写的栈,模拟栈 */ public class MyStackOwn { @Test public void test(){ push("A"); push("B"); push("C"); System.out.println(pop()); System.out.println(peek()); System.out.println(pop()); } private Object[] os=new Object[16]; private int size=0;//当前的栈占用大小,每次都+1 public void push(Object data){ if(size>=os.length){ resize();//当当前栈的占用大小大于对象数组的容量时,进行扩容 } os[size++]=data; } public void resize(){ Object []temp=new Object[os.length*3]; for(int i=0;i<os.length;i++){ temp[i]=os[i];//将当前栈逐个赋给临时栈 os[i]=null;//逐个释放当前栈 } os=temp; } public Object pop(){ Object o=os[size-1];//处理索引和size关系,否则越界 os[--size]=null; return o; } public Object peek(){ Object o=os[size-1];//处理索引和size关系,否则越界 return o; } }
找到栈中最小元素,写一个方法getMin():
package com.zxc.stacklearning; import org.junit.Test; import java.util.Stack; /** * Created by Administrator on 2018/2/16 0016. * 找到栈中最小值 */ public class StackGetMin { private Stack<Integer> stackData=new Stack<>(); private Stack<Integer> stackMin=new Stack<>(); public void push(Integer data){ if(stackMin.isEmpty()){ stackMin.push(data); }else if(data<=getMin()){ stackMin.push(data); } stackData.push(data); } public Integer getMin(){ return stackMin.peek(); } @Test public void test(){ push(1); push(2); push(3); System.out.println(getMin()); } }
中缀转后缀:迪杰斯特拉双栈算法:
package com.zxc.stacklearning; import org.junit.Test; import java.util.Stack; /** * Created by Administrator on 2018/2/16 0016. * 迪杰斯特拉双栈算法,中缀转后缀表达式 */ public class DijstraStack { @Test public void test(){ Stack<Integer> vals=new Stack<>();//数栈 Stack<Character> op=new Stack<>();//操作数栈 String s="((1+(2+3)*2)"; char []cs=s.toCharArray(); for(int i=0;i<cs.length;i++){ if(cs[i]=='+'){//push操作符 op.push(cs[i]); }else if(cs[i]=='-'){//push操作符 op.push(cs[i]); }else if(cs[i]=='*'){//push操作符 op.push(cs[i]); }else if(cs[i]=='/'){//push操作符 op.push(cs[i]); }else if(cs[i]=='('){ }else if(cs[i]==')') { Integer v=vals.pop();//弹出操作数 char c=op.pop();//弹出操作符 if(c=='+'){ v=v+vals.pop(); }else if(c=='-'){ v=vals.pop()-v; }else if(c=='*'){ v=v*vals.pop(); }else if(c=='/'){ v=vals.pop()/v; } vals.push(v); }else {//进入运算数 vals.push(Integer.parseInt(cs[i] + "")); } } System.out.println(vals.peek()); } }