栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用pop()和push()的堆栈数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用pop()和push()的堆栈数组

为您的Stack实施提供更好的解决方案

import java.util.List;import java.util.ArrayList;public class IntegerStack{    private List<Integer> stack;    public IntegerStack(int SIZE)     {        stack = new ArrayList<Integer>(SIZE);    }    public void push(int i)     {       stack.add(0,i);     }     public int pop()      {         if(!stack.isEmpty()){int i= stack.get(0);stack.remove(0);return i;        } else{return -1;// Or any invalid value        }     }     public int peek()     {        if(!stack.isEmpty()){return stack.get(0);        } else{return -1;// Or any invalid value        }     }     public boolean isEmpty()      {       stack.isEmpty();     } }

如果您必须使用Array …这是您的代码中的问题以及可能的解决方案

import java.util.Arrays;public class IntegerStack {    private int stack [];    private int top;    public IntegerStack(int SIZE)    {    stack = new int [SIZE];    top = -1; // top should be 0. If you keep it as -1, problems will arise when SIZE is passed as 0.     // In your push method -1==0 will be false and your pre will try to add the invalid element to Stack ..          }public void push(int i) {    if (top == stack.length)    {        extendStack();    }       stack[top]= i;        top++;}public int pop() {    top --; // here you are reducing the top before giving the Object back        return stack[top];}public int peek(){    return stack[top]; // Problem when stack is empty or size is 0    }public boolean isEmpty() {    if ( top == -1); // problem... we changed top to 0 above so here it need to check if its 0 and there should be no semicolon after the if statement       {        return true;    }}private void extendStack(){    int [] copy = Arrays.copyOf(stack, stack.length); // The second parameter in Arrays.copyOf has no changes, so there will be no change in array length.       }     }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610140.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号