栈
Posted on栈
栈**
博客分类:
【栈】 是限定仅在表尾进行插入或删除操作的线性表 表尾称为栈顶,表头称为栈底 特点:后进先出
操作: 1.推入push 2.弹出pop
栈的数组实现
- public class ArrayStack
{ - private List
list = new ArrayList (); - public boolean isEmpty(){
- return list.size()==0;
- }
- public void push(E element){
- list.add(element);
- }
- public void pop(){
- list.remove(list.size()-1);
- }
- public E getPop(){
- return list.get(list.size()-1);
- }
- public List
getElements(){ - List
result = new ArrayList (); - for(E e : list){
- result.add(((Element)e).getValue());
- }
- return result;
- }
- }
栈的链表实现
- public class LinkedStack
{ - private static class Node
{ - E element;
- Node
next; - public Node(E element){
- this.element = element;
- }
- }
- private Node
top = new Node (null); - private int size = 0;
- public boolean isEmpty() {
- return size == 0;
- }
- public void push(E element){
- Node
newNode = new Node (element); - if(!isEmpty()){
- newNode.next = getPopNode();
- top.next = newNode;
- }else{
- top.next = newNode;
- }
- size++;
- }
- public void pop(){
- if(isEmpty()){
- throw new RuntimeException("The stack is empty");
- }
- Node
firstNode = top.next; - top.next = firstNode.next;
- firstNode.next = null;
- size--;
- }
- public E getPop(){
- return getPopNode().element;
- }
- private Node
getPopNode(){ - if(isEmpty()){
- throw new RuntimeException("The stack is empty");
- }
- return top.next;
- }
- public List
getElements(){ - if(isEmpty()){
- return null;
- }else{
- List
elements = new ArrayList (); - Node
node = (Node ) top; - while(node.next!=null){
- node = node.next;
- elements.add(((Element)node.element).getValue());
- }
- return elements;
- }
- }
- }
来源: [http://tangyanbo.iteye.com/blog/1472830](http://tangyanbo.iteye.com/blog/1472830)