Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a FIFO queue in C

Tags:

c

stack

queue

Is it possible to create a FIFO 'stack' in C without using 2 stacks?

Thanks!

(Sorry to those who answered the previous one. I was thinking LIFO and meaning FIFO.)

like image 506
Tyler Avatar asked Jan 30 '09 22:01

Tyler


People also ask

What is FIFO in C programming?

FIFO is an abbreviation for first in, first out. It is a method for handling data structures where the first element is processed first and the newest element is processed last.

Is there queue in C?

A queue in C is basically a linear data structure to store and manipulate the data elements. It follows the order of First In First Out (FIFO). In queues, the first element entered into the array is the first element to be removed from the array.

Does C have built in stack?

No. The C11 standard does not contain the word stack , nor does it contain the word heap . That means it does not require either by name.

Is FIFO a stack or queue?

Queue: First In First Out (FIFO): The first object into a queue is the first object to leave the queue, used by a queue. Stack: First In Last Out (FILO): The first object or item in a stack is the last object or item to leave the stack.


2 Answers

It's very easy. Just implement a doubly-linked list, holding the pointer to the last item in the list.

To add to the queue, create a new node at the beginning, linking it to the previous beginning. (normal list insert)

To remove from the queue, deref the pointer to the last item, change the pointer to the previous-item pointer, and return the last item... (This is why the doubly-linked list. The other option is a singly-linked list and iterating the whole list to get pointers to the last two elements).

like image 61
user54650 Avatar answered Sep 20 '22 17:09

user54650


It sounds like you're trying to make a queue, where you insert at one end and pull from the other.

One way to do that is with a linked list. You can store pointers to the head and tail. When you insert, append the new record to the tail and when you pop something off the queue, you grab the node pointed to by the head pointer. (Or vice verse, it doesn't much matter)

like image 28
Dana Avatar answered Sep 17 '22 17:09

Dana