Posted on

**

博客分类:

【栈】 是限定仅在表尾进行插入或删除操作的线性表 表尾称为栈顶,表头称为栈底 特点:后进先出

操作: 1.推入push 2.弹出pop

栈的数组实现

Java代码 收藏代码

  1. public class ArrayStack {
  2. private List list = new ArrayList();
  3. public boolean isEmpty(){
  4. return list.size()==0;
  5. }
  6. public void push(E element){
  7. list.add(element);
  8. }
  9. public void pop(){
  10. list.remove(list.size()-1);
  11. }
  12. public E getPop(){
  13. return list.get(list.size()-1);
  14. }
  15. public List getElements(){
  16. List result = new ArrayList();
  17. for(E e : list){
  18. result.add(((Element)e).getValue());
  19. }
  20. return result;
  21. }
  22. }

栈的链表实现

Java代码 收藏代码

  1. public class LinkedStack{
  2. private static class Node{
  3. E element;
  4. Node next;
  5. public Node(E element){
  6. this.element = element;
  7. }
  8. }
  9. private Node top = new Node(null);
  10. private int size = 0;
  11. public boolean isEmpty() {
  12. return size == 0;
  13. }
  14. public void push(E element){
  15. Node newNode = new Node(element);
  16. if(!isEmpty()){
  17. newNode.next = getPopNode();
  18. top.next = newNode;
  19. }else{
  20. top.next = newNode;
  21. }
  22. size++;
  23. }
  24. public void pop(){
  25. if(isEmpty()){
  26. throw new RuntimeException("The stack is empty");
  27. }
  28. Node firstNode = top.next;
  29. top.next = firstNode.next;
  30. firstNode.next = null;
  31. size--;
  32. }
  33. public E getPop(){
  34. return getPopNode().element;
  35. }
  36. private Node getPopNode(){
  37. if(isEmpty()){
  38. throw new RuntimeException("The stack is empty");
  39. }
  40. return top.next;
  41. }
  42. public List getElements(){
  43. if(isEmpty()){
  44. return null;
  45. }else{
  46. List elements = new ArrayList();
  47. Node node = (Node) top;
  48. while(node.next!=null){
  49. node = node.next;
  50. elements.add(((Element)node.element).getValue());
  51. }
  52. return elements;
  53. }
  54. }
  55. }

来源: [http://tangyanbo.iteye.com/blog/1472830](http://tangyanbo.iteye.com/blog/1472830)

希望本站内容对您有点用处,有什么疑问或建议请在后面留言评论
转载请注明作者(RobinChia)和出处 It so life ,请勿用于任何商业用途
本文链接: