代码
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} Node;
typedef struct Queue {
Node *head, *tail;
} Queue;
Node *initNode(int val) {
Node *n = (Node *)malloc(sizeof(Node));
if (!n) return NULL;
n->val = val;
n->next = NULL;
return n;
}
void freeNode(Node *p) {
if (p) free(p);
return ;
}
Queue *initQueue() {
Queue *q = (Queue *)malloc(sizeof(Queue));
q->head = NULL, q->tail = NULL;
return q;
}
void freeQueue(Queue *q) {
if (!q) return ;
Node *p = q->head, *k;
while (p) {
k = p;
p = p->next;
freeNode(k);
}
free(q);
return ;
}
int push(Queue *q, int val) {
if (!q) return 0;
Node *n = initNode(val);
if (!n) return 0;
if (q->tail) {
q->tail->next = n;
q->tail = n;
} else
q->head = n, q->tail = n;
return 1;
}
int isEmpty(Queue *q) {
return !(q && q->head);
}
int pop(Queue *q) {
Node *k = q->head;
int tmp = k->val;
q->head = k->next;
freeNode(k);
if (!q->head) q->tail = NULL;
return tmp;
}
#if 0
typedef struct Queue {
int *data, size, head, tail;
} Queue;
int expand(Queue *q);
Queue *initQueue(int n) {
Queue *q = (Queue *)malloc(sizeof(Queue));
q->data = (int *)malloc(sizeof(int) * n);
q->size = n;
q->head = 0;
q->tail = 0;
}
void freeQueue(Queue *q) {
if (!q) return ;
free(q->data);
free(q);
return ;
}
int push(Queue *q, int val) {
if (!q) return 0;
if ((q->tail + 1) % q->size == q->head) {
if (!expand(q)) return 0;
}
q->data[q->tail] = val;
q->tail = (q->tail + 1) % q->size;
return 1;
}
int isEmpty(Queue *q) {
return !q || q->head == q->tail;
}
int pop(Queue *q) {
int tmp = q->data[q->head];
q->head = (q->head + 1) % q->size;
return tmp;
}
int expand(Queue *q) {
if (!q) return 0;
int expsize = q->size, *tmp;
while (expsize) {
tmp = (int *)malloc(sizeof(int) * (q->size + expsize));
if (tmp) break;
expsize >>= 1;
}
if (!tmp) return 0;
int i, j;
for (i = q->head, j = 0; i != q->tail; i = (i +1) % q->size, ++j)
tmp[j] = q->data[i];
free(q->data);
q->data = tmp, q->head = 0, q->tail = j, q->size += expsize;
printf("expand successfully~, new size is %d\n", q->size);
return 1;
}
#endif
int main() {
return 0;
}
|