您的位置:首页 > 理论基础 > 数据结构算法

数据结构 JAVA描述(二) 栈

2015-12-23 00:21 627 查看

一、栈的抽象数据类型描述

IStack

package Stack;

public interface IStack {

public void clear();

public boolean isEmpty();

public int length();

public Object peek();

public void push(Object x) throws Exception;

public Object pop();

public void display();

}


二、顺序栈

SqStack

package Stack;

public class SqStack implements IStack {
private Object[] stackElem;
//在非空栈中,top始终指向栈顶元素的下一个存储位置;当栈为空时,top值为0
private int top;

public SqStack(int maxSize) {
top = 0;
stackElem = new Object[maxSize];
}

public void clear() {
top = 0;
}

public boolean isEmpty() {
return top == 0;
}

public int length() {
return top;
}

/**
* @description 取栈顶元素
* @return
* @time 2015年12月23日 上午12:10:15
*/
public Object peek() {
if (!isEmpty()) {
return stackElem[top - 1];
} else
return null;
}

/**
* @description 入栈
* @param x
* @throws Exception
* @time 2015年12月23日 上午12:11:59
*/
public void push(Object x) throws Exception {
if (top == stackElem.length)
throw new Exception("栈已满");
else
stackElem[top++] = x;
}

/**
* @description 出栈
* @return
* @time 2015年12月23日 上午12:12:09
*/
public Object pop() {
if (isEmpty())
return null;
else
return stackElem[--top];
}

public void display() {
for (int i = top - 1; i >= 0; i--) {
System.out.println(stackElem[i].toString());
}
}

}


三、链栈

Node

package Stack;

// 链栈的结点结构
class Node {
private Object data;
private Node next;

public Node() {
this(null);
}

public Node(Object data) {
this.data = data;
this.next = null;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}
}


LinkStack

public class LinkStack implements IStack {
private Node top;

public void clear() {
top = null;
}

public boolean isEmpty() {
return top == null;
}

public int length() {
Node p = top;
int length = 0;
while (p != null) {
p = p.getNext();
++length;
}
return length;
}

public Object peek() {
if (!isEmpty())
return top.getData();
else
return nu
4000
ll;
}

/**
* @description 入栈
* @param x
* @time 2015年12月23日 上午12:19:39
*/
public void push(Object x) {
Node p = new Node(x);
p.setNext(top);
top = p;
}

/**
* @description 出栈
* @return
* @time 2015年12月23日 上午12:19:48
*/
public Object pop() {
if (isEmpty())
return null;
else {
Node p = top;
top = top.getNext();
return p.getData();
}
}

public void display() {
Node p = top;
while (p != null) {
System.out.println(p.getData().toString() + " ");
p = p.getNext();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 数据结构