标签:int top 栈顶 System 算法 println public
算法-1:栈
-
push(入栈)
-
pop(出栈)
-
top(栈顶)
-
特点:后进先出
-
题目:请你实现一个栈。
- push x:将 加x 入栈,保证 x为 int 型整数。
- pop:输出栈顶,并让栈顶出栈
- top:输出栈顶,栈顶不出栈
-
代码
import java.util.Scanner;
/**
* @author : JiangShan
* @version : 1.0
* @ClassName :
* @Date : Created in 13:46 2022/5/29
* 栈
* 请你实现一个栈。
* 操作:
* push x:将 加x 入栈,保证 x为 int 型整数。
* pop:输出栈顶,并让栈顶出栈
* top:输出栈顶,栈顶不出栈
*/
public class Main {
public static void main(String... args) {
// 获取输入
Scanner sc = new Scanner(System.in);
//valueof() 返回指定对象原始值
int size = Integer.valueOf(sc.nextLine());
JimStack stack = new JimStack(size);
// 判断输入
String tempStr;
String[] tempArr;
while (sc.hasNextLine()) {
tempStr = sc.nextLine();
tempArr = tempStr.split(" ");
// 是否通过输入校验
boolean isSuccess = isPrintSuccess(tempArr);
if (!isSuccess) continue;
if ("push".equals(tempArr[0])) {
stack.push(tempArr[1]);
continue;
}
if ("pop".equals(tempArr[0])) {
stack.pop();
continue;
}
if ("top".equals(tempArr[0])) {
stack.top();
continue;
}
}
sc.close();
}
/**** 判断输入是否通过验证 **/
public static boolean isPrintSuccess(String[] printArr) {
if (printArr.length == 0) {
System.out.println("error");
return false;
}
String first = printArr[0];
if ("pop".equals(first) || "push".equals(first) ||
"top".equals(first) ) return true;
// 其他情况不通过验证
System.out.println("error");
return false;
}
}
// 自定义实现一个栈
class JimStack {
int maxSize;
int top = -1;
int[] data;
public void push(String value) {
top ++;
data[top] = Integer.valueOf(value);
}
public void pop() {
if (top == -1){
System.out.println("error");
return;
}
int value = data[top];
System.out.println(value);
top--;
}
public void top() {
if (top == -1) {
System.out.println("error");
return ;
}
System.out.println(data[top]);
}
public JimStack(int maxSize) {
this.maxSize = maxSize;
this.data = new int[maxSize];
}
}
题目详解转自牛客网用户 “牛客353928144号”,最重要的是将后进先出 以及top(栈顶),pop(出栈),push(入栈)的理念用算法表现出来,而且用有参构造器圈定了数组长度,nb!!
class JimStack {
int maxSize;
int top = -1;
int[] data;
public void push(String value) {
top ++;
data[top] = Integer.valueOf(value);
}
public void pop() {
if (top == -1){
System.out.println("error");
return;
}
int value = data[top];
System.out.println(value);
top--;
}
public void top() {
if (top == -1) {
System.out.println("error");
return ;
}
System.out.println(data[top]);
}
public JimStack(int maxSize) {
this.maxSize = maxSize;
this.data = new int[maxSize];
}
}
标签:int,top,栈顶,System,算法,println,public 来源: https://www.cnblogs.com/jiangshan1314/p/16323891.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。