栈---链表实现

来源:互联网 发布:数据近义词 编辑:程序博客网 时间:2024/05/29 20:01

栈--链表实现:

package org.zp.datastruct;public class LinkedStack implements Stack {// 链表节点类private static class SLLNode {private Object data;private SLLNode next;public SLLNode() {}public SLLNode(Object data) {this.data = data;}public SLLNode(Object data, SLLNode next) {this.data = data;this.next = next;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}public SLLNode getNext() {return next;}public void setNext(SLLNode next) {this.next = next;}public String toString() {return data.toString();}}private SLLNode top;private int count;public LinkedStack() {        // 初始化 空栈,栈深度任意clear();}@Overridepublic void clear() {top = null;count = 0;}@Overridepublic boolean isEmpty() {return top == null;}@Overridepublic Object peek() {if (top == null) {throw new IllegalStateException();}return top.data;}@Overridepublic Object pop() {if (top == null) {throw new IllegalStateException();}Object val = top.data;top = top.next;count--;return val;}@Overridepublic void push(Object obj) {top = new SLLNode(obj, top);count++;}@Overridepublic int size() {return count;}public String toString() {String buf = "[ ";for (SLLNode curr = top; curr != null; curr = curr.next) {if (curr != top) {buf += ", ";}buf += curr.data;}buf += " ]";return buf;}}




原创粉丝点击