1. 程式人生 > >Data Structures and Algorithms (English) - 6-1 Deque(25 分)

Data Structures and Algorithms (English) - 6-1 Deque(25 分)

題目連結:點選開啟連結

 

題目大意:注意這裡的 Last 相當於 Pre 的意思。

 

解題思路:略。

 

AC 程式碼

Deque CreateDeque()
{
    PtrToNode nd=(PtrToNode)malloc(sizeof(struct Node));
    Deque deq=(Deque)malloc(sizeof(struct DequeRecord));
    nd->Next=nd->Last=NULL;
    deq->Front=deq->Rear=nd;
    return deq;
}

int Push(ElementType X, Deque D)
{
    PtrToNode nd=(PtrToNode)malloc(sizeof(struct Node));
    if(!nd) return 0;
    nd->Element=X;
    nd->Last=D->Front;
    nd->Next=D->Front->Next;
    if(D->Front->Next) D->Front->Next->Last=nd;
    D->Front->Next=nd;
    if(D->Front==D->Rear) D->Rear=nd;
    return 1;
}

int Inject(ElementType X, Deque D)
{
    PtrToNode nd=(PtrToNode)malloc(sizeof(struct Node));
    if(!nd) return ERROR;
    nd->Element=X;
    nd->Next=NULL;
    D->Rear->Next=nd;
    nd->Last=D->Rear;
    if(D->Rear==D->Front) D->Front->Next=nd;
    D->Rear=nd;
    return 1;
}

ElementType Pop(Deque D)
{
    if(D->Front==D->Rear) return ERROR;
    PtrToNode nd=D->Front->Next;
    if(D->Front->Next==D->Rear) D->Rear=D->Front;
    D->Front->Next=D->Front->Next->Next;
    ElementType tmp;
    tmp=nd->Element;
    free(nd);
    return tmp;
}

ElementType Eject(Deque D)
{
    if(D->Front==D->Rear) return ERROR;
    PtrToNode nd=D->Rear;
    ElementType tmp=nd->Element;
    D->Rear=D->Rear->Last;
    free(nd);
    return tmp;
}