zoukankan      html  css  js  c++  java
  • 用栈操作实现队列的操作

    原文链接:点击打开链接

    用栈实现下列队列操作:

    • push(x)  在队列末尾添加元素x
    • pop()      删除队列首的元素
    • peek()   返回队列首元素但不删除它
    • empty() 判断队列是否为空
    struct Queue {
        int data;
        struct Queue* next;
    };
    
    typedef struct Queue Queue;
    
    /* Create a queue */
    void queueCreate(Queue *queue, int maxSize) {
        
        queue = (Queue*)malloc(sizeof(Queue));
        queue->next = NULL;
        Queue* end_of_queue = queue;
        
        while (maxSize--) {
            
            int data_in_node;
            Queue* q = (Queue*)malloc(sizeof(Queue));
            if (NULL == q)
                break;
            
            printf("Please input the data of this node: ");
            scanf("%d", &data_in_node);
            
            q->next      = end_of_queue->next;
            q->data      = data_in_node;
            end_of_queue->next  = q;
            end_of_queue = q;
        }
    }
    
    /* Push element x to the back of queue */
    void queuePush(Queue *queue, int element) {
        
        Queue* q    =   (Queue*)malloc(sizeof(Queue));
        if (NULL == q)
            return ;
        Queue* end  =   queue->next;
        
        while (NULL != end->next)
            end = end->next;
            
        q->next     =   end->next;
        end->next   =   q;
    }
    
    /* Removes the element from front of queue */
    void queuePop(Queue *queue) {
        if (NULL == queue->next)
            return;
            
        Queue* top  = queue->next;
        queue->next = top->next;
        free(top);
    }
    
    /* Get the front element */
    int queuePeek(Queue *queue) {
        
        if (NULL == queue->next)
            return -1;
        return (queue->next->data);
    }
    
    /* Return whether the queue is empty */
    bool queueEmpty(Queue *queue) {
        
        return (NULL == queue->next);
    }
    
    /* Destroy the queue */
    void queueDestroy(Queue *queue) {
        
        if (NULL == queue->next)
            return ;
        
        Queue* ds     = queue->next;
        Queue* dsNext = ds->next;
        
        while (NULL != dsNext->next) {
            
            free(ds);
            ds = dsNext;
            dsNext = dsNext->next;
        }
        
        free(dsNext);
        queue->next = NULL;
    }
    


  • 相关阅读:
    hadoop 执行python 注意的地方
    ADOBE FLASH BUILDER 4.6 IOS 开发之离线地图
    ADOBE FLASH BUILDER 4.6 IOS 开发之地图控件
    Flex 4.6 ADT 工具编译异常
    Web中的广告组件(幻灯片组件)实现
    [译]《学习HTML5游戏编程》第二章
    自适应两栏布局的最简实现
    [译]InfoQ1205
    [译]《学了HTML5游戏编程》前言
    [译]InfoQ1201
  • 原文地址:https://www.cnblogs.com/averson/p/5096056.html
Copyright © 2011-2022 走看看