• 习题3.26双端队列


    #include<stdio.h>
    #include<stdlib.h>
    
    struct Node;
    struct Queue;
    
    typedef struct Node * PtrToNode;
    typedef struct Queue * PtrToQ; 
    
    struct Node{
        PtrToNode Pre;
        PtrToNode Next;
        ElemenType Ele;
    }
    
    struct Queue{
        PtrToNode front;
        PtrToNode rear;
    };
    
    PtrToQ
    CreateDQ( void )
    {
        PtrToQ Q;
        Q = malloc( sizeof( struct Queue ) );
        
        Q->front = malloc( sizeof( struct Node ) );
        Q->front->pre = NULL;
        
        Q->rear = malloc( sizeof( struct Node ) );
        Q->rear->Next = NULL;
        
        Q->front->Next = Q->rear;
        Q->rear->Pre = Q->front;
        return Q;
    }
    
    void
    Push( ElementType X, PtrToQ Q )
    {
        PtrToNode TmpCell;
        TmpCell = malloc( sizeof( struct Node ) );
        /* 连接后面 */
        TmpCell->Next = Q->front->Next;
        TmpCell->Next->pre = TmpCell;
        /* 连接前面 */
        Q->front->Next = TmpCell;
        TmpCell->pre = Q->front;
    }
    
    ElementType
    Pop( PtrToQ Q )
    {
        PtrToNode TmpCell;
        ElementType res;
        if( !IsEmpty() )
        {
            TmpCell = Q->front->Next;
            Q->front->Next = TmpCell->Next;
            TmpCell->Next->pre = Q->front;
            res = TmpCell->Ele;
            free( TmpCell );
            return res;
        }
        else
            Error;
    }
    
    void
    Inject( ElementType X, PtrToQ Q )
    {
        PtrToNode TmpCell;
        TmpCell->Ele = X;
        /* 左边 */
        TmpCell->pre = Q->rear->pre;
        TmpCell->pre->Next = TmpCell;
        /* 右边 */
        TmpCell->Next = Q->rear;
        Q->rear->pre = Tmpcell;
    }
    
    ElementType
    Eject( PtrToQ Q )
    {
        if( !IsEmpty( Q ) ){
        PtrToNode TmpCell;
        ElementType res;
        TmpCell = Q->rear->pre;
        TmpCell->pre->Next = Q->rear;
        Q->rear->pre = TmpCell->pre;
        res = TmpCell->Ele;
        free(TmpCell);
        return res;
        }
        else
            Error;
    }
    View Code

    以上使用链表做两端都可以插入删除元素的双端队列

    初始状态为两个表头的双链表

    IsEmpty:判断队列是否只有两个结点

  • 相关阅读:
    兼容利器之X-UA-Compatible
    SQL Server之游标的基础知识
    SQL 按特定字段值排序
    NodeJS 开篇 牛刀小试
    临时表之IF-ELSE
    css中如何设置字体
    怎么做到不加班?
    C# .net中cookie值为中文时的乱码解决方法
    HTML5商城开发一 楼层滚动加载数据
    QQ浏览器X5内核问题汇总
  • 原文地址:https://www.cnblogs.com/gabygoole/p/4694829.html
Copyright © 2020-2023  润新知