单链表实现栈
思路
使用链表模拟栈
思路:
入栈:当要插入数据时,直接将其放在头节点之后
newNode.next = head.next; head.next = newNode;
出栈:删除返回头节点的下一个节点,
StackNode data = head.next;
head.next = head.next.next;
return data.value;
遍历:list(),从头节点开始遍历
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| class LinkedListStack { private StackNode head; private int maxSize; private int size = 0;
public LinkedListStack(int maxSize) { this.head = new StackNode(null, 0); this.maxSize = maxSize; }
public boolean isFull() { return size == maxSize; }
public boolean isEmpty() { return head.next == null; }
public void push(int value) { if (isFull()) { System.out.println("栈已满,无法放入!!!!!"); return; } StackNode newNode = new StackNode(value); if (!isEmpty()) { newNode.next = head.next; } head.next = newNode; size++; }
public int pop() { if (isEmpty()) { throw new RuntimeException("大兄弟,栈是空的!!!!!"); } StackNode node = head.next; head.next = head.next.next; size--; return node.value; }
public void list(){ if (isEmpty()) { System.out.println("大兄弟,栈是空的!!!!!"); return; } StackNode temp = head.next; System.out.println("遍历所有值"); while (temp!=null) { System.out.println("stack:"+temp.value); temp = temp.next; } }
class StackNode { StackNode next; int value; public StackNode(int value) { this.value = value; } public StackNode(StackNode next, int value) { this.next = next; this.value = value; } } }
|
数组实现栈
思路
定义一个maxSize,表示栈的大小
使用一个top指针,来表示栈顶元素;
入栈时,top++,arr[top] = 新元素;
出栈时,,arr[top]就是要出栈的元素,然后top–;
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| class ArrayStack{ private int maxSize; private int[] stack; private int top;
public ArrayStack(int maxSize){ if (maxSize<=0) { System.out.println("maxSize的值不合法!"); return; } this.top = -1; this.maxSize = maxSize; stack = new int[this.maxSize]; }
public boolean isFull(){ return top == maxSize - 1; }
public boolean isEmpty(){ return top==-1; }
public void push(int value){ if (isFull()) { throw new RuntimeException("栈已满"); } stack[++top] = value; }
public int pop(){ if (isEmpty()) { throw new RuntimeException("栈为空"); } return stack[top--]; }
public void list(){ if (isEmpty()) { System.out.println("栈是空的,大兄弟!!"); } for (int i = top;i>=0;i--) { System.out.printf("stack[%d] = %d\n",i,stack[i]); } } }
|