【資料結構】隊列-數組的實現,資料結構隊列數組
首先定義隊列的基本結構,隊列和棧不同之處在於隊列需要兩個指標,一個指向頭,一個指向尾
String[] queue;int front = 0;int rear = 0;
構造方法
public QueueOfStrings(int capacity) {queue = new String[capacity];}
進隊列
public void enqueue(String str) {queue[rear++] = str;if (rear == queue.length)resize(2 * queue.length);}
出隊列
public String dequeue() {return queue[front++];}
判空
public boolean isEmpty() {return front == rear;}
判滿
public boolean isFull() {return rear == queue.length;}
尺寸
public int size() {return rear - front;}
最後附上resize
public void resize(int capacity) {String[] copy = new String[capacity];for (int i = 0; i < rear; i++)copy[i] = queue[i];queue = copy;}
用數組實現棧與隊列的資料結構
#include <stdlib.h>
#include <stdio.h>
class Stack
{
private:
int ele[100];
int top;
public:
Stack() {
top = 0;
}
void push(int v) {
ele[top++] = v;
}
int pop() {
if(isEmpty()) {
printf("The stack is Empty.\n");
return -1;
}
return ele[--top];
}
bool isEmpty() {
return top == 0;
}
~Stack() {
}
};
#define SIZE 100
class Queue
{
private:
int ele[SIZE];
int head;
int tail;
public:
Queue() {
head = 0;
tail = 0;
}
bool isFull() {
return (tail+1) % SIZE == head;
}
bool isEmpty() {
return head == tail;
}
void enqueue(int val) {
if(isFull()) {
printf("The queue is full, can not enqueue for: %d\n", val);
return;
}
ele[tail] = val;
tail = (tail+1) %SIZE;
}
int dequeue() {
if(isEmpty()) {
printf("The queue is empty, can not dequeue.\n");
return -1;
}
int value = ele[head];
head = (head+1)%SIZE;
return value;
}
};
int main()
{
Stack s;
s.push(123);
s.push(12);
while(!s.isEmpty()) {
printf("%d ", s.pop());
}
printf("\n");
Queue q;
q.enqueue(88);
q.enqueue(13);
q.enqueue(123);
while(!q.isEmpty()) printf("%d ", q.dequeue());
printf("\n");
system("pause");
}...餘下全文>>
資料結構設計隊列實現下列演算法
#include <stdio.h>
#include <stdlib.h>
typedef struct QNode
{
int data;
struct QNode *next;
int Queusize;
}
QNode,*QueuePtr;//定義隊列結點類型
typedef struct
{
QueuePtr front;
QueuePtr rear;
}
LinkQueue;//隊列的類型
void InitQueue(LinkQueue *Q)//建立隊列
{
Q->front=Q->rear=(QueuePtr)malloc(sizeof(QNode));
Q->front->next=NULL;
}
void EnQueue(LinkQueue *Q,int e)//將元素插入隊列
{
QueuePtr p;
p=(QueuePtr)malloc(sizeof(QNode));
p->data=e;
p->next=NULL;
Q->rear->next=p;
Q->rear=p;
}
int DeQueue(LinkQueue *Q)//將元素出列且返回元素的位置
{
int e;
QueuePtr p;
p=Q->front->next;
e=p->data;
Q->front->next=p->next;
if(Q->rear==p)
Q->rear=Q->front;
free(p);
return (e);
}
int QueueEmpty(LinkQueue *Q)//判斷隊列是否為空白
{
if(Q->front==Q->rear )
return 1;
else
return 0;
}
void Select(LinkQueue *Q,int a)
{
int b,i;QueuePtr p;
if(a==1)
{
printf("請輸入元素,以0結束:\n");
scanf("%d",&b);
while(b!=0)
{
EnQueue(Q,b);
scanf("%d",&b);
}
}
if(a==2)
{
printf("請輸入出對元素個數\n");
scanf("%d",&b);
for(i=0;i<b;i++)
{
if(!QueueEmpty(Q))
DeQueue(Q);
else
printf("隊列為空白!\n");break;
}
}
if(a==3)
{
printf("隊內元素為\n");
......餘下全文>>