Java中的数据结构(1)----栈和队列

来源:互联网 时间:1970-01-01

马上要找工作了,数据结构貌似是笔试的必考题,所以要复习一遍。

首先是栈--先进后出

package com.wz.util;public class Stack<T> {private int MAX;private int top;private T []stack;Stack (int max){MAX = max;stack = (T[])new Object [MAX];top = -1;}//入栈public int push(T t){int value = -1;if(top >= MAX-1){System.out.println("stack is full!");value = 0; // 表示栈已满}else{top++;stack[top] = t;value = 1;}return value;}//出栈public T pop(){if(top<0){System.out.println("stack is empty!");return null; //栈空}else{top --;return stack[top+1]; //返回弹出值}}}

队列--先进先出

package com.wz.util;public class Queue<T> {private int front; //对头private int rear; //队尾private int MAX;private T [] queue;Queue(int max){MAX = max;queue = (T [])new Object[MAX];rear = -1;front = 0;}//入队public int enQueue(T t){int value = -1;if(rear >=MAX-1){System.out.println("Queue is full!");value = 0;}else{rear ++;queue[rear] = t;value = 1;}return value;}//出队public T deQueue(){if(front>rear){System.out.println("Queue is empty!");return null;}else{front++;return queue[front-1];}}}

相关阅读:
Top