zoukankan      html  css  js  c++  java
  • 算法导论12:队列的链表实现 2016.1.12

      普通的链表队列和栈的实现差不多,只是修改一下进出的规则即可。(感觉自己就像在翻译算法导论的伪代码一样。。不过还好吧,也有一点自己的理解)

      下面是代码:

    #include<stdio.h>
    #include<stdlib.h>
    
    typedef struct _node{
        int num;
        struct _node *next;
    }node;
    
    struct queue {
        node * head;
        node * tail;
    }Q;
    
    void build(struct queue &Q)
    {
        Q.tail=(node *)malloc(sizeof(node));
        Q.tail->next=NULL;
        Q.head=(node *)malloc(sizeof(node));
        Q.head->next=Q.tail;
    }
    
    int Qempty(struct queue &Q)
    {
        if ((Q.head)->next==Q.tail) return 1;
        else return 0;
    }
    
    int dequeue(struct queue &Q)
    {
        if (Qempty(Q)) {
            printf("空队列!
    ");
        }
        else {
            node *p;
            p=Q.head;
            Q.head=(Q.head)->next;
            int k=p->num;
            free(p);
            return k;
        }
    }
    
    void init(struct queue &Q)
    {
        while (!Qempty(Q)) {
            dequeue(Q);
        }
    }
    
    void enqueue(struct queue &Q,int n)
    {
        node *p;
        p=(node *)malloc(sizeof(node));
        p->num=n;
        p->next=Q.head;
        Q.head=p; 
    }
    
    void showqueue(struct queue Q)
    {
        while ((Q.head)->next!=Q.tail){
            int k=(Q.head)->num;
            Q.head=(Q.head)->next;
            printf("|%d|
    ",k);
        }
        printf("| |
    ");
    }
    
    int main()
    {
        printf("1:初始化队列;2:入队列;3:出队列;4:退出。
    ");
        build(Q);
        int n;
        while (1) {
            int k;
            scanf("%d",&k);
            switch(k) {
                case 1:init(Q); break;
                case 2:scanf("%d",&n); enqueue(Q,n); break;
                case 3:dequeue(Q); break;
                case 4:return 0;
            }
            showqueue(Q);
        }    
        return 0;
    }
  • 相关阅读:
    Vue之仿百度搜索框
    Vue之交互
    Vue之键盘事件
    Vue之事件冒泡
    Vue之阻止默认行为
    sql注入常用注释符总结
    什么是Git
    Github部署博客
    php笔记
    JavaScript(更新中)
  • 原文地址:https://www.cnblogs.com/itlqs/p/5123918.html
Copyright © 2011-2022 走看看