Thursday, 5 May 2011

Stack using One Queue

Implement a stack using a queue. The operations need not be neccesarily O(1).


#include "queueimplll.h"

typedef struct queue QUEUE;
typedef struct queue_node QUEUE_NODE;

int queuepush( QUEUE *q1, int val)
{

/* In an empty Q, push the val straight*/
if (q1->first == 0 &&
q1->last == 0)
{
enqueue( q1, val);
return 0;
}

/* enQ val*/
if (enqueue(q1, val))
{
printf("ERROR: enqueue q2\n");
}


/* deQ, enQ by 1 short of QLength*/
int first_value;
int qlength = queue_length(q1) - 1;
while(qlength--)
{
dequeue(q1, &first_value);
enqueue(q1, first_value);
}

return 0;
}

/*Driver Program*/
int main()
{
QUEUE queue1;
int index;

init_queue(&queue1);

for (index = 10; index <= 100; index += 10)
{
queuepush( &queue1, index);
}

int value = 0;
index = 0;
while (!queue_empty_p(&queue1))
{
dequeue( &queue1, &value);
printf("%d : %d\n", index++, value);
}
}

No comments:

Post a Comment