Java数据结构 - 栈

韩顺平2019-Java数据结构

学习韩顺平老师的Java数据结构

栈特点

1.先入后出
2.变化的一端叫栈顶(TOP)固定的一端叫栈底(Bottom)
3.出栈(pop)和入栈(push)

数组模拟栈

思路:
1使用数组模拟
2.使用top表示栈顶 ,初始化-1
3.入栈
top++
stack(top) = data;
4.出栈
int value = stack[top];
top–;
reyurn value;

package com.stack;

/**
 * 〈数组模拟栈>
 * @author PitterWang
 * @create 2019/12/21
 * @since 1.0.0
 */
public class ArrayTack {

	private int maxSize;
	private int[] stack;
	private int top = -1;

	public ArrayTack(int maxSize){
		this.maxSize = maxSize;
		stack = new  int[this.maxSize];
	}

	public boolean isFull(){
		return top == maxSize-1;
	}

	public boolean isEmpty(){
		return top == -1;
	}

	public void push(int value){
		if(isFull()){
			System.out.printf("栈满");
			return;
		}

		top++;
		stack[top] = value;
	}

	public int pop(){
		if(isEmpty()){
			throw new RuntimeException("栈空");
		}
		int value = stack[top];
		top--;
		return value;
	}

	public void list(){
		if(isEmpty()){
			System.out.println("栈空");
			return;
		}

		System.out.println("top = " + top);
		for(int i = top; i>=0; i--){
			System.out.printf(" stack[%d] = %d \n",i, stack[i]);
		}
	}


	/***
	 * 返回当前栈顶
	 */
	public int peek(){
		return stack[top];
	}
}
列表模拟栈

课后作业–由于是按照自己的思路写的,有问题请大家提出。

package com.stack;

/**
 * 〈链表模拟栈〉
 *
 * @author PitterWang
 * @create 2019/12/21
 * @since 1.0.0
 */
public class LindedListTask {

	private Node headNode;

	/**
	 * 链表为空
	 * @return
	 */
	public boolean isEmpty(){
		return headNode == null;
	}

	public void push(Object object){

		Node node = new Node();
		node.setObject(object);

		if(isEmpty()){
			headNode = node;
			return;
		}
		node.setNextNode(headNode);
		headNode = node;
	}


	public Object pop(){
		Object object = null;

		if(isEmpty()){
			System.out.println("队列为空");
			return object;
		}


		object = headNode.getObject();
		headNode = headNode.getNextNode();

		return object;
	}

	public void list(){
		if(isEmpty()){
			System.out.println("空");
			return;
		}
		Node temp = headNode;
		while (true){
			if(temp == null){
				break;
			}
			System.out.println(temp.getObject());

			temp = temp.getNextNode();
		}
	}
}

github 源码地址:自学数据结构源码地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值