0
点赞
收藏
分享

微信扫一扫

day14--栈

i奇异 2022-04-16 阅读 83
java

1.栈

2.入栈操作

  • 首先判断栈是否满
  • 若栈未满,先将数据入栈,然后深度再+1
public boolean push(char paraChar) {
		if (depth == MAX_DEPTH) {
			System.out.println("Stack full.");
			return false;
		}

		data[depth] = paraChar;
		depth++;

		return true;
	}// of push

3.出栈操作

  • 先判断栈是否为空
  • 若栈不为空,将栈底元素赋值给resultChar
public char pop() {
		if (depth == 0) {
			System.out.println("Nothing to pop.");
			return '\0';
		} 

		char resultChar = data[depth - 1];
		depth--;

		return resultChar;
	}// of pop

4.完整代码实现

package com.datastructure;

public class CharStack {
	
	public static final int MAX_DEPTH = 10;

	int depth;

	char[] data;

	public CharStack() {
		depth = 0;
		data = new char[MAX_DEPTH];
	}// of the first constructor

	public String toString() {
		String resultString = "";
		for (int i = 0; i < depth; i++) {
			resultString += data[i] + " ";
		} // of for i

		return resultString;
	}// of toString

	//入栈
	public boolean push(char paraChar) {
		if (depth == MAX_DEPTH) {
			System.out.println("Stack full.");
			return false;
		}

		data[depth] = paraChar;
		depth++;

		return true;
	}// of push

	//出栈
	public char pop() {
		if (depth == 0) {
			System.out.println("Nothing to pop.");
			return '\0';
		} 

		char resultChar = data[depth - 1];
		depth--;

		return resultChar;
	}// of pop

	public static void main(String args[]) {
		CharStack tempStack = new CharStack();

		for (char ch = 'a'; ch < 'm'; ch++) {
			tempStack.push(ch);
			System.out.println("The current stack is: " + tempStack);
		} // of for ch

		char tempChar;
		for (int i = 0; i < 12; i++) {
			tempChar = tempStack.pop();
			System.out.println("Poped: " + tempChar);
			System.out.println("The current stack is: " + tempStack);
		} // of for i
	}// of main
}// of class

代码效果:

在这里插入图片描述

举报

相关推荐

day 14

day_14

day14

Python-day14

day14-异常

Day14 IO

Oracle day14

DAY 14 | 自学前端第14天

Day 14 Homework2

0 条评论