Chinaunix首页 | 论坛 | 博客
  • 博客访问: 516191
  • 博文数量: 118
  • 博客积分: 10028
  • 博客等级: 上将
  • 技术积分: 1820
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-07 18:46
文章分类

全部博文(118)

文章存档

2009年(12)

2008年(106)

我的朋友

分类: C/C++

2008-12-30 00:56:47



队列的实现

用链表来实现,两个结构体,一个是节点,一个用于控制队列,有插入节点、删除节点、输出队列几个功能

P.S: fflush(stdin)在VC可以用,GCC不行,可以写几句代码来代替~
代码

/* implement a queue
 * functions:insert,delete,print
 */

#include <stdio.h>
#include <stdlib.h>

struct node{ //nodes of queue

    int key;
    struct node *next;
};
typedef struct node Node;

struct qu{ //the controller of the queue

    Node *front;
    Node *rear;
};
typedef struct qu Queue;

Queue *init_queue(Queue *Q)
{
    Q=(Queue *)malloc(sizeof(Queue));
    if(NULL == Q){
        printf("Mlloc error!\n");
        exit(1);
    }
    Q->front=Q->rear=NULL;

    return Q;
}

void enQueue(Queue *Q,int data)
{
    Node *temp;

    temp=(Node *)malloc(sizeof(Node));
    if(NULL == temp){
        printf("Malloc error!\n");
        exit(1);
    }
    temp->key=data;
    temp->next=NULL;

    if(NULL == Q->rear){//the queue is empty

        Q->front=Q->rear=temp;
    }else{
        Q->rear->next=temp;
        Q->rear=temp;
    }
}

void deQueue(Queue *Q)
{
    Node *p;

    if(NULL == Q->front){
        printf("Empty!\n");
        return;
    }
    if(Q->front == Q->rear){//delete the latest node

        Q->rear=NULL;
    }
    p=Q->front;
    Q->front=Q->front->next;
    printf("Delet date:%d \n",p->key);
    free(p);
}

void print_queue(Queue *Q)
{
    Node *p=Q->front;

    if(NULL == p){
        printf("The queue is empty!\n");
        return;
    }
    while(p){
        printf("%d ",p->key);
        p=p->next;
    }
    printf("\n");
}

int main(int argc,char **argv)
{
    int data;
    char e;
    Queue *Q=NULL;

    Q=init_queue(Q);

    while(1){
        fflush(stdin);
        printf("Input the operator(i-insert,d-delete,p-print,q-quit):");
        scanf("%c",&e);

        switch(e){
            case 'i':
                fflush(stdin);
                printf("Input a number:");
                scanf("%d",&data);
                enQueue(Q,data);
                break;
            case 'd':
                deQueue(Q);
                break;
            case 'p':
                print_queue(Q);
                break;
            case 'q':
                return 0;
                break;
            default:
                printf("Unknown Operator!\n");
        }
    }
    return 0;
}

阅读(760) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~