花间一壶酒

导航

栈-链式存储-Java实现

package com.wrh.lab.dataStructure.stackAndQueue;

/**
* the interface of the SeqStack
*
@author wrh
*
*
@param <E>
*/

public interface Stack<E> {

/**
* push the element to the stack
*
@param element
*/

public void push(E element);

/**
* pop the element from the stack and
* return the pop element
*/

public E pop();

/**
*
*
@return the top value
*/

public E getTop();

/**
*
*
@return true for empty and false for not empty
*/

public boolean isEmpty();

/**
* clear the stack
*/

public void clear();

}

 

package com.wrh.lab.dataStructure.stackAndQueue;

/**
*
*
@author wrh
* the stack node
*/

public class StackNode<E> {
private E element;
private StackNode<E> next;

/**
* constructor
*/

public StackNode() {
element = null;
next = null;
}

public StackNode(E element, StackNode<E> next) {
this.element = element;
this.next = next;
}

public E getElement() {
return element;
}

/**
*
@param element
*/

public void setElement(E element) {
this.element = element;
}

public StackNode<E> getNext() {
return next;
}

public void setNext(StackNode<E> next) {
this.next = next;
}

}

 

package com.wrh.lab.dataStructure.stackAndQueueImpl;
/**
*
@author wrh
* the implementation of the linked stack
*/

import com.trs.lab.dataStructure.stackAndQueue.Stack;
import com.trs.lab.dataStructure.stackAndQueue.StackNode;

public class LinkedStackImpl<E> implements Stack<E> {
private StackNode<E> top;
private int size;

//constructor
public LinkedStackImpl() {

top = null;
}

@Override
public void push(E element) {
top = new StackNode(element, top); //the next point to the former top and the new node is top
}


@Override
public E pop() {
if (null != top) {
E t = top.getElement();
top = top.getNext();
return t;
} else {
System.out.println("the stack is null");
return null;
}
}

@Override
public E getTop() {
if (isEmpty()) {
System.out.println("the stack is null");
return null;
} else {
return top.getElement();
}
}

@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return top == null;

}

@Override
public void clear() {
top = null;
}

public static void main(String[] args) {
Stack<Integer> s = new LinkedStackImpl<Integer>();
s.push(1);
s.push(2);
s.push(3);
//s.clear();
System.out.println(s.isEmpty());

System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
}




posted on 2012-02-16 17:14  wrh526  阅读(265)  评论(0编辑  收藏  举报