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

typedef struct node{
    int info;
    struct node * next;
}Node;

typedef Node * List;

struct queue{
    int size;
    List tail;
    List head;
};

typedef struct queue *Queue;


/* post: creates an empty queue */
Queue initqueue(){
    Queue q;
    q = malloc(sizeof(struct queue));
    q->tail = q->head = NULL;
    q->size = 0;
    return q;
}

/*post: returns 1 if the queue is empty 0 otherwise  */
int queueempty(Queue q){
    return (q->head) == NULL ? 1 : 0;
}

/*post: inserts an element at the end */
void enqueue(Queue q, int elem){
    List temp = (List)malloc(sizeof(Node));
    temp->info = elem;


    if(q->head == NULL){
        temp->next = q->head ;
        q->head = temp;
    }else{
        temp->next = q->tail;
        q->tail = temp;
    }
    (q->size)++;
}

/*pre: queue not empty */
/*post: returns and removes the first element of the queue */

int dequeue(Queue q){
    int ris;
    List temp;

    temp = q->head;
    q->head = q->head->next;
    ris = temp->info;
    free(temp);
    (q->size)--;

    return ris;
}

/*pre: queue not empty */
/*post: returns the first element of the queue */
int first(Queue q){
    return q->head != NULL ? q->head->info : -1;
}

/*post: returns the number of elements in the queue */
int sizequeue(Queue q){
    return q->size;
}


所以这就是我尝试使用喜欢的列表实现队列的方式。
问题是,每当我使用dequeue()函数时,我的q-> head指针都将变为NULL,因此我丢失了发生在此代码行周围的head:

q->head = q->head->next;


但是我不确定这是错误的行还是enqueue()函数错误,因为q-> head和q-> tail应该指向相同的链表,但是我猜嘿,所以我已经对其进行了测试一点,这就是我得到的:

如果我在非空队列上执行dequeue(),则first()函数返回-1(q-> head == NULL),然后如果我执行enqueue(q,10),则first()函数将返回10队列的开头,因此enqueue()将元素放在队列的前面而不是结尾的前面,我似乎无法理解什么地方出了问题。

如果有人可以帮助我整理一下我的代码,那将非常有用,谢谢。

最佳答案

1)添加第一个元素时不更新tail

2)添加其他元素的代码是错误的。

试试这个

void enqueue(Queue q, int elem){
    List temp = (List)malloc(sizeof(Node));
    temp->info = elem;
    temp->next = NULL;   // Always set next to NULL as you add to the tail


    if(q->head == NULL){
        q->head = temp;
        q->tail = temp;        // Also update tail
    }else{
        q->tail->next = temp;  // Make current tail element link the new element
        q->tail = temp;        // Update the tail to the new element
    }
    (q->size)++;
}

关于c - 用链表实现队列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41301095/

10-09 08:27
查看更多