如何按喜欢的列表编写出队的出队功能

时间:2018-10-09 11:13:40

标签: c queue

我正在尝试通过链表写入队列funtion dequeue

请帮助我,我被困住了。雕像减去了!!

http://codepad.org/9kAnwY0w中,您可以找到代码:

1 个答案:

答案 0 :(得分:0)

您使用单链列表,因此只能从头部出队。

如果要从尾部弹出,则需要使用双向链表

#include <stdio.h>
#include <stdlib.h>

typedef struct aNODE {
    int     data;
    struct aNODE    * pNext;
} NODE;

NODE    *rear, *front;
int count;

void initQueue()
{
    rear    = NULL;
    front   = NULL;
    count   = 0;
}


void enqueue(int data)
{
    NODE* newNode = (NODE *) malloc( sizeof(NODE) );
    newNode->pNext = NULL;
    newNode->data = data;

    /* TH1. Queue ban dau rong */
    if ( count == 0 )
    {
        front = newNode;
        rear = newNode;
        count++;
    } else { /* TH2. Khac rong */
        rear->pNext = newNode;
        rear = newNode;
        count++;
    }
}


NODE* dequeue()
{
    if (!front) 
    {
        return(NULL);
    }

    NODE* tmp = front;
    front = front->pNext;
    count--;
    return(tmp);
}

int size()
{
    return(count);
}

int main()
{
    initQueue();
    printf("size %d\n", size());
    for (int i = 0; i < 100; i++)
    {
        enqueue(i + 1);
    }

    printf("size %d\n", size());

    for (int i = 0; i < 50; i++)
    {
        dequeue();
    }

    printf("size %d\n", size());

    return(0);
}