• 算法导论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;
    }
  • 相关阅读:
    完全卸载 Oracle
    Windows 下 Oracle 10g 手工创建数据库
    zip & unzip 命令
    J2EE的13种核心技术规范
    Windows 8发行预览版序列号
    wget百度百科
    Application's Life Cycle
    当前网络存在的安全问题
    Ubuntu 11.10 更换 LightDM 开机登录画面
    tmp文件夹的默认权限
  • 原文地址:https://www.cnblogs.com/itlqs/p/5123918.html
Copyright © 2020-2023  润新知