1.使用数组方式
public static void main(String[] args) throws Exception {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));int operateNum = Integer.parseInt(br.readLine());//操作次数String inputInfo;//输入信息StringBuilder outputSb = new StringBuilder();//输出信息StackInner stackInner = new StackInner();stackInner.initCap(operateNum);for (int i = 0; i < operateNum; i++) {inputInfo = br.readLine();if ("top".equals(inputInfo)) {Integer topData = stackInner.top();if (topData == null) {outputSb.append("error").append("\n");} else {outputSb.append(topData).append("\n");}} else if ("pop".equals(inputInfo)) {Integer popData = stackInner.pop();if (popData == null) {outputSb.append("error").append("\n");} else {outputSb.append(popData).append("\n");}} else {stackInner.push(Integer.parseInt(inputInfo.split(" ")[1]));}}System.out.println(outputSb);}public static class StackInner {private int topIndex = 0;private Integer[] dataArray = null;public void initCap(int size) {dataArray = new Integer[size];}public void push(int data) {dataArray[topIndex] = data;topIndex++;}public Integer top() {if (topIndex > 0) {return dataArray[topIndex - 1];} else {return dataArray[topIndex];}}public Integer pop() {Integer topData = top();if (topData == null) {return null;}if (topIndex > 0) {dataArray[topIndex - 1] = null;topIndex--;} else {dataArray[topIndex] = null;}return topData;}}
2.使用链表方式
public static void main(String[] args) throws Exception {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));int operateNum = Integer.parseInt(br.readLine());//操作次数String inputInfo;//输入信息StringBuilder outputSb = new StringBuilder();//输出信息StackInner stackInner = new StackInner();for (int i = 0; i < operateNum; i++) {inputInfo = br.readLine();if ("top".equals(inputInfo)) {//topint topData = stackInner.top();if (topData == Integer.MIN_VALUE) {outputSb.append("error").append("\n");} else {outputSb.append(topData).append("\n");}} else if ("pop".equals(inputInfo)) {//popint popData = stackInner.pop();if (popData == Integer.MIN_VALUE) {outputSb.append("error").append("\n");} else {outputSb.append(popData).append("\n");}} else {//pushString[] inputInfoArray = inputInfo.split(" ");stackInner.push(Integer.parseInt(inputInfoArray[1]));}}System.out.println(outputSb);}//节点,使用链实现栈功能private static class Node {public Node(int num) {this.data = num;}public int data;//数据public Node nextNode;//下一个节点}//内部栈public static class StackInner {private Node headNode;//头节点public void push(Integer num) {if (headNode == null) {headNode = new Node(num);} else {Node newHead = new Node(num);newHead.nextNode = headNode;headNode = newHead;}}public int top() {if (headNode == null) {return Integer.MIN_VALUE;} else {return headNode.data;}}public int pop() {if (headNode == null) {return Integer.MIN_VALUE;} else {int popNum = headNode.data;Node newHeadNode = headNode.nextNode;headNode.nextNode = null;headNode = newHeadNode;return popNum;}}}
在牛客网上提交测试,最好运行时间在390ms左右