天天看點

隊列

隊列的基本操作有初始化隊列,判隊列是否為空,入隊,出隊

棧可分為兩種存儲結構:順序隊和鍊隊。

順序隊

/* 順序隊結構 */

typedef struct

{

ElemType data[MAXSIZE];

int front;

int rear;

} SqQueue;

順序隊四個要素:

(1)隊空條件:qu.rear == qu.front;

(2)隊滿條件: (qu.rear + 1) % MAXSIZE == qu.front;

(3)進隊條件: qu.rear = (qu.rear + 1) % MAXSIZE; qu.data[qu.rear] = data;

(4)出隊條件: qu.front = (qu.front + 1) % MAXSIZE; data = qu.data[qu.front];

順序隊基本操作

隊列
隊列

#include "stdafx.h"
#include <stdlib.h>

#define MAXSIZE 10

typedef int ElemType;

/* 順序棧結構 */
typedef struct 
{
    ElemType data[MAXSIZE];
    int front;
    int rear;
} SqQueue;

void InitStack(SqQueue &qu)
{
    qu.front = qu.rear = 0;
}

bool IsEmpty(SqQueue &qu)
{
    return (qu.front == qu.rear);
}

int InQueue(SqQueue &qu, ElemType data)
{
    if ((qu.rear + 1) % MAXSIZE == qu.front)
    {
        return -1;
    }
    
    qu.data[qu.rear] = data;
    qu.rear = (qu.rear+1) % MAXSIZE;
    
    return 0;
}

int OutQueue(SqQueue &qu, ElemType &data)
{
    if (qu.front == qu.rear)
    {
        return -1;
    }

    qu.front = (qu.front + 1) % MAXSIZE;
    data = qu.data[qu.front];    
    return 0;
}

void PrintQueue(SqQueue &qu)
{
    int i = 0;
    if (qu.front == qu.rear)
        return;

    i = qu.front;
    while (i != qu.rear)
    {
        printf("%d\t", qu.data[i]);
        i = (i+1)%MAXSIZE;
    }
    printf("\r\n");
    return;
}

int _tmain(int argc, _TCHAR* argv[])
{

    ElemType array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int i = 0;
    int data = 0;
    SqQueue queue = { 0 };

    InitStack(queue);
    for (i = 0; i < sizeof(array)/sizeof(ElemType); i++)
    {
        InQueue(queue, array[i]);
    }

    PrintQueue(queue);
    OutQueue(queue, data);
    OutQueue(queue, data);
    PrintQueue(queue);
    InQueue(queue, 11);
    InQueue(queue, 12);
    PrintQueue(queue);
    return 0;
}      

View Code