韩顺平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 源码地址:自学数据结构源码地址