您的位置:首页 > 理论基础 > 数据结构算法

数据结构—队列小结

2017-11-12 13:30 274 查看
队列

1动态数组队列

2链表队列

3两栈实现队列

4两队列实现栈

5前k个元素逆置

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
* Created by root on 17-11-12.
*/
public class 队列 {

}
class ListNode{
int val;
ListNode next;
}
//简化版的动态数组队列
class 动态数组队列{
private int front;
private int rear;
private int capacity;
private int size;
private int[] array;
动态数组队列(int capacity){
capacity=capacity;
front=0;
rear=0;
size=0;
array=new int[capacity];
}
public boolean isEmpty(){
return size==0;
}
public boolean isFull(){
return size==capacity;
}
public void enQueue(int data){
if (isFull()) resizeQueue();
else {
array[rear]=data;
rear=(rear+1)%capacity;
size++;
}
}
public int deQueue(){
if (isEmpty())return -1;
else {
int tmp = array[front];
front=(front+1)%capacity;
size--;
return tmp;
}
}
public void resizeQueue(){
int newCapacity = 2*capacity;
int[] newArray = new int[newCapacity];
for (int i=0;i<newCapacity;i++){
newArray[i]=array[i];
}
capacity=newCapacity;
array=newArray;
}
public int getSize(){
return size;
}
}
class 链表队列{
ListNode front;
ListNode rear;
链表队列(){
front=null;
rear=null;
}
public void enQueue(int data){
ListNode node = new ListNode();
node.val=data;
if (rear==null&&front==null){
rear=front=node;
}else {
rear.next=node;
rear=node;
}
}
public int deQueue(){
if (isEmpty())return -1;
else {
int tmp=front.val;
front=front.next;
return tmp;
}
}

private boolean isEmpty() {
return front==null;
}
}
class 两栈实现队列{
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public boolean isEmpty(){
return stack1.isEmpty()&&stack2.isEmpty();
}
public void enQueue(int data){
stack1.push(data);
}
public int deQueue(){
if (isEmpty())return -1;
if (stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
class 两队列实现栈{
动态数组队列 d1 = new 动态数组队列(10);
动态数组队列 d2 = new 动态数组队列(10);
public void push(int data){
d1.enQueue(data);
}
public int pop(){
if (d1.isEmpty()&&d2.isEmpty())return -1;
if (d2.isEmpty()){
while (d1.getSize()!=1){
d2.enQueue(d1.deQueue());
}
return d1.deQueue();
}else {
while (d2.getSize()!=1){
d1.enQueue(d2.deQueue());
}
return d2.deQueue();
}
}
}
class 前k个元素逆置{//队列和栈可以实现逆置的操作
Queue<Integer> queue = null;
Stack<Integer> stack = new Stack<>();
public 前k个元素逆置(int[] array){
queue=new LinkedList<>();
for (int i =0;i<array.length;i++){
queue.offer(array[i]);
}
}
public void reverseK(int k){
while (k--!=0){
stack.push(queue.poll());
}
while (!stack.isEmpty()){
queue.offer(stack.pop());
}
int n = queue.size()-k;
while (n--!=0){
queue.offer(queue.poll());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: