資料結構--隊列之C數組實現,資料結構--隊列數組
隊列是一種限定操作的線性表,它只能在表的一段插入,另外一段取出.
所以也稱為先進先出資料結構(FIFO---First In First Out)
C代碼如下(有小bug不想調了,作為參考即可):
#include<stdio.h>#define maxsize 5typedef int ElemType;typedef struct queue{ int head; int tail; ElemType Data[maxsize];}Queue;void InitQueue(Queue *Q){ Q->tail=0; Q->head=0;}void EnQueue(Queue *Q){ int value; int i; printf("Input Queue Value:\n"); scanf("%d",&value); Q->head++; int len=Q->head-Q->tail; if(len<maxsize) { for(i=len-1;i>=0;i--) Q->Data[i+1]=Q->Data[i]; } Q->Data[Q->tail]=value; printf("\n");}void DeQueue(Queue *Q){ int len=Q->head-Q->tail-1; Q->head=Q->head-1; if(len<=maxsize) { printf("Out put Value:\n"); printf("%d ",Q->Data[len]); } printf("\n");}void IsEmpty(Queue *Q){ if(Q->head==0&&Q->tail==0) printf("Queue is empty.\n"); else printf("Queue is not empet.\n "); printf("\n");}void IsFull(Queue *Q){ if(Q->head-Q->tail>=maxsize) printf("Queue is Full.\n"); else printf("Queue is not Full.\n"); printf("\n");}void main(){ Queue Q; InitQueue(&Q); EnQueue(&Q); EnQueue(&Q); EnQueue(&Q); EnQueue(&Q); EnQueue(&Q); IsEmpty(&Q); IsFull(&Q); DeQueue(&Q); DeQueue(&Q); DeQueue(&Q); DeQueue(&Q); DeQueue(&Q); IsEmpty(&Q); IsFull(&Q);}
結果圖:
轉載請註明作者:小劉
用數組實現棧與隊列的資料結構
#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");
}...餘下全文>>
資料結構(c語言版)隊列基本操作的實現
0.0