[java 算法与数据结构 栈和队列 ] 用数组实现栈

本文深入探讨了栈数据结构的实现,包括整数型栈的创建、压栈与出栈操作,以及如何使用栈进行字符串逆序。通过具体代码示例和测试用例,详细解析了栈的工作原理和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1.整数型栈 

2.用栈实现字符串逆序

1.对应第4章

栈只允许访问一个数据项,移除这个项才可以访问下一个项。

push 压栈 向栈顶填入一个项,  pop移除栈顶  top 箭头指向当前栈顶位置。

1.整数型栈 

 


package com.java.base;

/**
 * Created by zengjx on 2019/3/4.
 */

public class StackX {
    private    int   maxSize;
    private   long[]   stackArray;
    private    int  top ;//栈顶
    public    StackX(int  s){
      this.maxSize =s;
      stackArray  =new  long[maxSize];
      top=-1;//初始值
        System.out.println("   init  top "+top);
    }
    //压栈
     public   int   push(long  j){
      if(top<maxSize-1){
            stackArray[++top]=j;
        }else{
            return -1;//栈满
        }
     //   System.out.println(" top= "+top);
         return  0;
     }
    //出栈
     public    long pop(){
         if(top>-1){
           long  temp =stackArray[top];
              stackArray[top]=0;
              top--;
          return temp;
         }else{
            return   -1;
         }
     }
     public   boolean  isEmpty(){
       boolean   isFlag=false;
        if(top==-1){
            isFlag=true;
        }
       return   isFlag;
     }
     public   boolean   isFull(){
         boolean   isFlag=false;
          if(top==maxSize-1){
              isFlag=true;
          }
         return   isFlag;
     }

    public     void  print() {
        if(stackArray==null|| stackArray.length<1){
            return;
        }
        if(stackArray.length>0){
            StringBuffer  sb=  new  StringBuffer();
            for(int i=0;i<stackArray.length;i++){
                sb.append(" "+stackArray[i]);
            }
            System.out.println(" "+sb.toString());
        }
    }
     public    long[]   getArray(){

       return   stackArray;
     }
     public    int   getTop(){

         return   top;
     }
}
用例:
package com.java.base;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by zengjx on 2019/3/4.
 */
public class StackXTest {

    StackX  stackX  ;

    @Before
    public void setUp() throws Exception {
        stackX =new StackX(10);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void push() throws Exception {
        for(int  i=0;i<11;i++){
            stackX.push(100*(i+1));
        }
        System.out.println("是否栈满"+stackX.isFull()+   " 当前 top "+stackX.getTop());
        stackX.print();
        StringBuffer  sb= new StringBuffer();
        for(int  i=0;i<11;i++){
            long  temp= stackX.pop();
            sb.append(" "+ temp);
        }
        System.out.println("出栈 "+sb.toString());
        stackX.print();
        System.out.println( "isFull" +stackX.isFull()+"是否为空"+stackX.getTop()+" isEmpty "+stackX.isEmpty());
    }

    @Test
    public void pop() throws Exception {



    }

    @Test
    public void isEmpty() throws Exception {
    }

    @Test
    public void isFull() throws Exception {
    }

    @Test
    public void print() throws Exception {
    }

}

输出结果:

 init  top -1
是否栈满true 当前 top 9
  100 200 300 400 500 600 700 800 900 1000
出栈  1000 900 800 700 600 500 400 300 200 100 -1
  0 0 0 0 0 0 0 0 0 0
isFullfalse是否为空-1 isEmpty true
   init  top -1
   init  top -1

2.用栈实现字符串逆序:

package com.AlgorithmDemo;

import java.util.Stack;

/**
 * Created by zengjx on 2019/3/7.
 */

public class StackX {
    private    int iSize;//栈大小
    private    char[]  array;
    private    int  top;//top标识 指向栈顶
    private    int   iNum;//当前栈里面成员个数
    public StackX(int   iSize){
     array   =new char[iSize];
       this.iSize=iSize;
     int  top =-1;
     int  iNum=0;
    }
   //压栈
    public  int    push(char  x){
        int  iRet=0;
        if(iNum<iSize-1){
            array[++top]=x;
            iNum++;
        }else{
            iRet =-1;
        }
       return  iRet;
    }
//  出栈
    public   char  pop(){
        char  cRet='0';
        if(iNum>0){
          cRet=array[top--];
          iNum--;
        }else{
         top=-1;
        }
        return cRet;
    }
//栈空判断
public   boolean  isEmpty(){
        return (iNum==0);
    }
//栈满判断
    public    boolean  isFull(){

        return   (iNum==iSize-1);

    }

    public    char[]   peekArray(){

        return array;

    }


}

 

package com.AlgorithmDemo;

import org.junit.Before;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Array;

import static org.junit.Assert.*;

/**
 * Created by zengjx on 2019/3/7.
 */
public class StackXTest {

    StackX  stackX;
    @Before
    public void setUp() throws Exception {
        stackX=new StackX(10);

    }

    @Test
    public void push() throws Exception {
     /*   System.out.println(" Enter  a string:");
        System.out.flush();
        InputStreamReader   isr =new InputStreamReader(System.in);
        BufferedReader     br=  new BufferedReader(isr);
        String input= br.readLine();*/
         String  input ="123456789011111111";
        for(int  i=0;i<input.length();i++){
           char   in = input.charAt(i);
           int  iRet= stackX.push(in);
           if(iRet!=0){
               boolean  bRet=stackX.isFull();
               if(bRet==true){
                   System.out.println(" isFull  bRet="+bRet);
               }
               break;
           }
        }
        char[]   ret=stackX.peekArray();
        StringBuffer  sb= new StringBuffer();
        for(char  out :ret){
            sb.append(out);
        }
        System.out.println(" push:"+sb.toString());
        StringBuffer   stringBuffer=new StringBuffer();
        while (!stackX.isEmpty()){
            char  sg= stackX.pop();
            stringBuffer.append(sg);

        }
        System.out.println("pop:"+stringBuffer.toString());
    }

    @Test
    public void pop() throws Exception {
    }

    @Test
    public void isEmpty() throws Exception {
    }

    @Test
    public void isFull() throws Exception {
    }

    @Test
    public void peekArray() throws Exception {
    }

}

 输出结果:

目录

1.整数型栈 

2.用栈实现字符串逆序:

3.分隔符匹配


package com.AlgorithmDemo;

import java.util.Stack;

/**
 * Created by zengjx on 2019/3/7.
 */

public class StackX {
    private    int iSize;
    private    char[]  array;
    private    int  top;
    private    int   iNum;
    public StackX(int   iSize){
     array   =new char[iSize];
       this.iSize=iSize;
       top =-1;
     int  iNum=0;
    }
    public  int    push(char  x){
        int  iRet=0;
        if(iNum<=iSize){
            array[++top]=x;
            iNum++;
        }else{
            iRet =-1;
        }
       return  iRet;
    }
    public   char  pop(){
        char  cRet='0';
        if(iNum>0){
          cRet=array[top--];
          iNum--;
        }else{
         top=-1;
        }
        return cRet;
    }
    public   boolean  isEmpty(){
        return (iNum==0);
    }
    public    boolean  isFull(){

        return   (iNum==iSize-1);

    }
    public    char[]   peekArray(){

        return array;

    }
    public  boolean  check(String  input){
      //  boolean   bRet=true;
      if(input==null|| input.length()==0){
          return   false;
      }
      for(int i=0;i<input.length();i++){
          char  in =input.charAt(i);
        switch (in){
            case '{':
            case  '[':
            case  '(':
            {
                if(!isFull()){
                    push(in);
                }

            }
           break;
            case '}':
            case  ']':
            case  ')':
            {
                if(!isEmpty()){
                    char   out  =pop();
                    if((in=='{')&&(out!='}') ){
                        System.out.println("Err  "+"in "+in+" "+"out "+out);
                        return   false;
                    }
                    if((in=='[')&&(out!=']') ){
                        System.out.println("Err  "+"in "+in+" "+"out "+out);
                        return   false;
                    }
                    if((in=='(')&&(out!=')') ){
                        System.out.println("Err  "+"in "+in+" "+"out "+out);
                        return   false;
                    }
                }else{
                    System.out.println("Err   empty "+"in "+in);
                    return   false;

                }
            }
            break;
        }
      }
      if(isEmpty()){//遍历结束还有未匹配的左分割符
          return   true;
      }else{
          return  false;
      }

    }
} 
@Test
public void pop() throws Exception {
    //
    stackX=new StackX(10);
    String  input ="a{b(c[d]e)f";//   { ( [ ])
   boolean     ret=    stackX.check(input);
   System.out.println(" exp:false  check    ret :"+ret);

    input ="a{b(c[d]e)f";//   { ( [ ])
    ret=    stackX.check(input);
    System.out.println("   exp  false  check1    ret :"+ret);
    input ="a{b(c[d]e)f}}}}}";//   { ( [ ])
        ret=    stackX.check(input);
    System.out.println(" exp:false  check1    ret :"+ret);

    input ="{{{{{ 1}}}}}";//   { ( [ ])
        ret=    stackX.check(input);
    System.out.println(" exp:true  check1    ret :"+ret);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值