2016-12-23 3 views
0
#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; 
} 

このように私は好きなリストでキューを実装しようとします。好きなリストでキューを実装する

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

が、私はそれがこれですかどうかわからないです: 問題は、私はデキューを使用するときということですが()>ヘッドポインタがNULLになりそう私はこのコード行の周りに起こる頭部を失い、私のqの機能しますそれは間違っているか、またはq-> headとq-> tailが同じリンクリストを指している必要があるのでenqueue()関数が間違っている行ですが、ちょっとテストしてしまったので、

空ではないキューでdequeue()を実行すると、first()funtionは-1(q-> head == NULL)を返し、次にenqueue(q、10) enqueue()は要素をendの代わりにキューの前に置くように、キューの先頭として10を返します。私は何が間違っているのか分からないようです。

誰かが私のコードを整理して助けてくれるなら、非常に助かりました。ありがとうございました。他の要素を追加するための最初の要素

2)コードを追加するときは、tailを更新しない

+3

非空のリストに(エンキュー)ノードを挿入するためのコードを詳しく見てみましょう。そこに[ラバーダックのデバッグ](https://en.wikipedia.org/wiki/Rubber_duck_debugging)を使ってみてください。それを紙の上に描こうとする。 –

+0

私は少し絵を描きました。私は答えを得ました。昨日は、それを正しくするために階層を整えていました、ありがとう。 – Alex

答えて

0

1)が間違っています。

はこれを試してみてください代わりに

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)++; 
} 
+0

ありがとうございます – Alex

+0

'dequeue()'関数では、 'q-> head == NULL 'なら' q-> head = q-> head-> next; 'が問題になります。 '-1'を直接返すための余分なif-conditionを追加してください。 –