栈和队列
1,stack
先进后出
package com.aluo.structure.four; public class Stack { private int maxSize; private long[] a; private int top; public Stack(int maxSize) { maxSize = maxSize; a = new long[maxSize]; top = -1; } public void push(long value) { a[++top] = value; } public long pop() { return a[top--]; } public long peek() { return a[top]; } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (top == maxSize - 1); } }
stack测试类
package com.aluo.structure.four; public class TestStack { public static void main(String[] args) { Stack s = new Stack(5); s.push(1); s.push(2); s.push(3); s.push(7); s.push(7); while (!s.isEmpty()) { System.out.println(s.pop()); } } }
output:

2,队列
先进先出
package com.aluo.structure.four; public class Queue { private int maxSize; private long[] a; private int front; private int rear; private int nElements; public Queue(int maxSize) { maxSize = maxSize; a = new long[maxSize]; front = 0; rear = -1; nElements = 0; } public void insert(long value) { if (rear == maxSize - 1) { rear = -1; } a[++rear] = value; nElements++; } public long remove() { long temp = a[front++]; if (front == maxSize) { front = 0; } nElements--; return temp; } public boolean isEmpty() { return (nElements == 0); } public boolean isFull() { return (nElements == maxSize); } public long peekFront() { return a[front]; } public int getNElement() { return nElements; } }
队列测试类
package com.aluo.structure.four; public class TestQueue { public static void main(String[] args) { int maxSize = 10; Queue q = new Queue(maxSize); q.insert(2); q.insert(23); q.insert(26); q.insert(23); q.insert(27); q.remove(); q.remove(); while (!q.isEmpty()){ System.out.println(q.remove()); } } }
output:


浙公网安备 33010602011771号