浏览 2084 次
锁定老帖子 主题:自己动手写数据结构之栈
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2012-04-01
【栈】
栈的数组实现
public class ArrayStack<E> { private List<E> list = new ArrayList<E>(); 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<Integer> getElements(){ List<Integer> result = new ArrayList<Integer>(); for(E e : list){ result.add(((Element)e).getValue()); } return result; } }
栈的链表实现
public class LinkedStack<E>{ private static class Node<E>{ E element; Node<E> next; public Node(E element){ this.element = element; } } private Node<E> top = new Node<E>(null); private int size = 0; public boolean isEmpty() { return size == 0; } public void push(E element){ Node<E> newNode = new Node<E>(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<E> firstNode = top.next; top.next = firstNode.next; firstNode.next = null; size--; } public E getPop(){ return getPopNode().element; } private Node<E> getPopNode(){ if(isEmpty()){ throw new RuntimeException("The stack is empty"); } return top.next; } public List<Integer> getElements(){ if(isEmpty()){ return null; }else{ List<Integer> elements = new ArrayList<Integer>(); Node<E> node = (Node<E>) top; while(node.next!=null){ node = node.next; elements.add(((Element)node.element).getValue()); } return elements; } } }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |