赞
踩
- public class ArrayStack {
- private final String[] items;
- private final int capacity;
- private int index = 0;
-
- public ArrayStack(int capacity) {
- this.capacity = capacity;
- items = new String[capacity];
- }
-
- public boolean push(String item) {
- if (index == capacity) return false;
- items[index++] = item;
- return true;
- }
-
- public String pop() {
- if (index == 0) return null;
- return items[--index];
- }
-
- public static void main(String[] args) {
- ArrayStack stack = new ArrayStack(10);
- System.out.println("first pop:" + stack.pop());
- Assert.isTrue(stack.push("123"));
- Assert.equals("123", stack.pop());
- System.out.println(stack.pop());
- }
- }
- public class LinkedStack {
-
- //头结点是哨兵节点,不需要额外处理 null
- private ListNode current = new ListNode(null);
-
- public boolean push(String item) {
- ListNode next = new ListNode(item);
- //1. 给 cur 的next 赋值
- this.current.next = next;
- //2. 给 next 的 prev 赋值
- next.prev = current;
- //3. 当前指针指向下一个
- current = next;
- return true;
- }
-
- public String pop() {
- if (this.current.prev == null) {
- return null;
- }
- String val = current.val;
- current = current.prev;
- return val;
- }
-
-
- public static void main(String[] args) {
- LinkedStack stack = new LinkedStack();
- System.out.println("first pop:" + stack.pop());
- Assert.isTrue(stack.push("123"));
- Assert.equals("123", stack.pop());
- System.out.println("end:" + stack.pop());
- System.out.println("end:" + stack.pop());
- }
- }
-
- class ListNode {
- String val;
- ListNode next;
- ListNode prev;
-
- ListNode(String x) {
- val = x;
- }
- }
20 155 232 844 224 682 496.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。