栈:
MyStack.java
1. public class MyStack { 2. //栈的底层我们用数组存储数据 3. int[] elements; 4. 5. public MyStack() { 6. elements = new int[0]; 7. } 8. //压入元素 9. public void push(int element){ 10. //创建一个新数组 11. int[] newArr = new int[elements.length + 1]; 12. //把原数组的值复制到新数组中 13. for (int i = 0; i < elements.length; i++) { 14. newArr[i] = elements[i]; 15. } 16. //把添加的元素放入新数组中 17. newArr[elements.length] = element; 18. //使用新数组替换旧数组 19. elements = newArr; 20. } 21. //取出栈顶元素 22. public int pop(){ 23. if (elements.length ==0){ 24. throw new RuntimeException("stack is Empty"); 25. } 26. //取出数组中最后一个元素 27. int element = elements[elements.length-1]; 28. //创建一个新数组 29. int[] newArr = new int[elements.length-1]; 30. for (int i = 0; i < elements.length-1; i++) { 31. newArr[i] = elements[i]; 32. } 33. elements = newArr; 34. return element; 35. } 36. //查看栈顶元素 37. public int peek(){ 38. return elements[elements.length-1]; 39. } 40. //判断栈顶是否为空 41. public boolean isEmpty(){ 42. return elements.length == 0; 43. } 44. }
Test.java
1. public class Test { 2. public static void main(String[] args) { 3. MyStack ms = new MyStack(); 4. ms.push(3); 5. ms.push(6); 6. ms.push(4); 7. ms.push(45); 8. System.out.println("栈顶元素是"+ms.peek()); 9. ms.pop(); 10. System.out.println("栈顶元素是"+ms.peek()); 11. System.out.println(ms.isEmpty()); 12. } 13. 14. }
测试结果:
队列:
MyQueue.java
1. public class MyQueue { 2. int[] elements; 3. public MyQueue() { 4. elements = new int[0]; 5. } 6. public void add(int element){ 7. int[] newArr = new int[elements.length+1]; 8. for (int i = 0; i < elements.length; i++) { 9. newArr[i] = elements[i]; 10. } 11. newArr[elements.length] = element; 12. elements = newArr; 13. } 14. public int poll(){ 15. if (elements.length == 0){ 16. throw new RuntimeException("queue is Empty"); 17. } 18. int element = elements[0]; 19. int[] newArr = new int[elements.length - 1]; 20. for (int i = 0; i < elements.length - 1; i++) { 21. newArr[i] = elements[i+1]; 22. } 23. elements = newArr; 24. return element; 25. } 26. public boolean isEmpty(){ 27. return elements.length == 0; 28. } 29. 30. }
Test.java
1. public class Test { 2. public static void main(String[] args) { 3. MyQueue mq = new MyQueue(); 4. mq.add(1); 5. mq.add(4); 6. mq.add(5); 7. mq.add(45); 8. System.out.println(mq.poll()); 9. System.out.println(mq.poll()); 10. System.out.println(mq.poll()); 11. System.out.println(mq.poll()); 12. System.out.println(mq.isEmpty()); 13. 14. } 15. 16. 17. }
测试结果: