栈和队列
栈和队列都是抽象数据类型(abstract data type,ADT),它们既可以用数组实现,又可以用链表实现。
1. 栈
1)栈模型
栈和队列都是抽象数据类型(abstract data type,ADT),它们既可以用数组实现,又可以用链表实现。
1. 栈
1)栈模型
栈(Stack,又LIFO:后进先出)是一种只能在固定的一端进行插入和删除的数据结构。栈只允许访问一个数据项:即最后插入的数据项,移除这个数据项后才能访问倒数第二个插入的数据项,以此类推。栈可以用数组来实现,也可以用链表来实现。
2)栈的数组实现
栈的Java代码:
public class MyStack { private long[] arr; //底层使用数组实现 private int top; public MyStack() { arr = new long[10]; top = -1; } public MyStack(int maxSize) { arr = new long[maxSize]; top = -1; } // put item on top of stack
public void push(long value) { arr[++top] = value;
} // take item from top of stack public long pop() { return arr[top--]; } // peek at top of stack public long peek() { return arr[top]; } // ture if stack is empty
public boolean isEmpty() {
return (top == -1); } // ture if stack is full public boolean isFull() { return (top == arr.length-1); } } 测试栈的特性: public void testMyStack() throws Exception {
MyStack myStack = new MyStack(4);
myStack.push(12);
myStack.push(34);
myStack.push(56);
myStack.push(78); System.out.println(myStack.isFull()); // true
while(!myStack.isEmpty()) {
System.out.print(myStack.pop()); //78, 56, 34, 12 if(!myStack.isEmpty()) { System.out.print(", "); } } System.out.println(); System.out.println(myStack.isFull()); // false }
2. 队列 1)队列模型 队列(Queue,又FIFO:先进先出)是一种插入时在一端进行而删除时在另一端进行的数据结构。 为解决顺序队列假溢出问题,而采用循环队列:即让队头、队尾指针在达到尾端时,又绕回到开头。2)队列的数组实现 队列的Java代码: public class MyQueue { private long[] arr; private int size; private int front; private int rear; public MyQueue() { arr = new long[10]; size = 0; front = 0; rear = -1; } public MyQueue(int maxSize) { arr = new long[maxSize]; size = 0; front = 0; rear = -1; } // put item at rear of queue public void insert(long value) { if(isEmpty()) { // throw exception if queue is full throw new ArrayIndexOutOfBoundsException(); } if(rear == arr.length-1) { //deal with wraparound (环绕式处理) rear = -1; } arr[++rear] = value; // increment rear and insert size++; // increment size } // take item from front of queue public long remove() { long value = arr[front++]; // get value and increment front if(front == arr.length) { // deal with wraparound front = 0; } size--; // one less item return value; }
// peek at front of queue public long peek() { return arr[front]; } // true if queue is empty public boolean isEmpty() { return (size == 0); } // true if queue is full public boolean isFull() { return (size == arr.length); } } 测试队列的特性: public void testMyQueue() throws Exception { MyQueue myQueue = new MyQueue(4); myQueue.insert(12); myQueue.insert(34); myQueue.insert(56); myQueue.insert(78); System.out.println(myQueue.isFull()); // true while(!myQueue.isEmpty()) { System.out.print(myQueue.remove()); //12, 34, 56, 78 if(!myQueue.isEmpty()) { System.out.print(", "); } } System.out.println(); System.out.println(myQueue.isEmpty()); // true myQueue.insert(99); System.out.println(myQueue.peek()); // 99 }