#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node
{
int val;
struct Node* next;
}Node;
typedef struct Queue
{
Node* head;
Node* tail;
}Queue;
Node* initNode(int val)
{
Node* n = (Node*)malloc(sizeof(Node));
n->val = val;
n->next = NULL;
return n;
}
void freeNode(Node* n)
{
if (n) free(n);
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;
}
bool push(Queue* q, int val)
{
if (!q) return 0;
Node* n = initNode(val);
if (q->tail)
{
q->tail->next = n;
q->tail = n;
}
else
{
q->head = n;
q->tail = n;
}
return true;
}
bool isEmpty(Queue* q)
{
return !(q && q->head);
}
int pop(Queue* q)
{
Node* k = q->head;
int t = k->val;
q->head = k->next;
freeNode(k);
if (!q->head) {
q->tail = NULL;
}
return t;
}
void showQueue(Queue* q)
{
if (!q) return;
printf("Stack:[");
Node* p = q->head;
while (p)
{
printf("%d->", p->val);
p = p->next;
}
printf("NULL]\n");
return;
}
int main()
{
srand(time(0));
Queue* q = initQueue();
int cnt = 20;
while (cnt--)
{
int val = rand() % 100;
int op = rand() % 4;
switch (op)
{
case 0:
case 1:
case 2:
printf("push %d,res=%s\n", val, push(q, val) ? "SUS" : "ERR");
break;
case 3:
isEmpty(q) ? printf("pop nothing!\n") : printf("pop %d \n", pop(q));
}
showQueue(q);
}
return 0;
}
08-19
952
08-20
306