题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Objects;
//push x:将 加x 入栈,保证 x 为 int 型整数
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
Stack stack = new Stack();
int totalOperate = 0;
List<String> inputLineList = new ArrayList<>();
int operateCount = 0;
while (in.hasNextLine()) {
String line = in.nextLine();
int isOperateCount = isOperateCount(line);
if (isOperateCount != -1) {
totalOperate = isOperateCount;
inputLineList = new ArrayList<>(totalOperate);
} else {
operateCount++;
inputLineList.add(line);
}
if (operateCount == totalOperate) {
break;
}
}
if (totalOperate != 0) {
for (int i = 0; i < inputLineList.size(); i++) {
String stackOperate = inputLineList.get(i);
int isOperateCount = isOperateCount(stackOperate);
if (isOperateCount == -1) {
if (stackOperate.contains("push")) {
String[] lineArray = stackOperate.split(" ");
int value = Integer.parseInt(lineArray[1]);
stack.push(value);
} else if (stackOperate.contains("pop")) {
int popValue = stack.pop();
if (popValue == -1) {
System.out.println("error");
} else {
System.out.println(popValue);
}
} else if (stackOperate.contains("top")) {
int topValue = stack.top();
if (topValue == -1) {
System.out.println("error");
} else {
System.out.println(topValue);
}
}
}
}
}
}
public static int isOperateCount(String line) {
try {
return Integer.parseInt(line);
} catch (Exception e) {
return -1;
}
}
public static class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setNext(Node next) {
this.next = next;
}
public Node getNext() {
return next;
}
}
public static class Stack {
private Node head;
private Node tail;
private int length = 0;
public void push(int value) {
length++;
if (head == null) {
head = new Node(value);
head.next = null;
tail = head;
} else {
Node next = head;
head = new Node(value);
head.next = next;
}
}
public int pop() {
if (length == 0) {
return -1;
} else {
length--;
int popValue = head.value;
head = head.next;
return popValue;
}
}
public int top() {
if (length == 0) {
return -1;
} else {
int popValue = head.value;
return popValue;
}
}
}
}
#java##栈#
查看1道真题和解析