File tree Expand file tree Collapse file tree 1 file changed +129
-0
lines changed
Expand file tree Collapse file tree 1 file changed +129
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Speedster3030, 2025
3+ * Ring Buffer/Circular Queue structure implementation.
4+ */
5+
6+ #include <stdio.h>
7+ #include <stdlib.h>
8+
9+ //ring Buffer/Circular Queue struct
10+ typedef struct
11+ {
12+ int * arr ;
13+ int count ;
14+ int head ;
15+ int tail ;
16+ int max ;
17+ }ringBuffer ;
18+
19+ //Initialize a new ring buffer
20+ ringBuffer * new_ringBuffer (int size )
21+ {
22+ ringBuffer * rb = malloc (sizeof (ringBuffer ));
23+
24+ rb -> max = size ;
25+ rb -> arr = malloc (size * sizeof (int ));
26+ rb -> count = 0 ;
27+ rb -> head = size - 1 ;
28+ rb -> tail = size - 1 ;
29+
30+ return rb ;
31+ }
32+
33+ //free the structure from memory
34+ void delete_Buffer (ringBuffer * * rb )
35+ {
36+ free ((* rb )-> arr );
37+ free (* rb );
38+ * rb = NULL ;
39+ }
40+
41+ //Put a value in the buffer
42+ int enqueue (ringBuffer * rb ,int n )
43+ {
44+ if (rb -> count == rb -> max )
45+ {
46+ return -1 ;
47+ }
48+
49+ rb -> arr [rb -> tail ]= n ;
50+ rb -> tail -- ;
51+ if (rb -> tail == -1 )
52+ {
53+ rb -> tail = rb -> max - 1 ;
54+ }
55+ rb -> count ++ ;
56+ return 0 ;
57+ }
58+
59+ //remove a value from the buffer
60+ int dequeue (ringBuffer * rb ,int * result )
61+ {
62+ if (rb -> count == 0 )
63+ {
64+ return -1 ;
65+ }
66+
67+ int t = rb -> arr [rb -> head ];
68+ rb -> arr [rb -> head ]= 0 ;
69+ rb -> head -- ;
70+ rb -> count -- ;
71+ if (rb -> head == -1 )
72+ {
73+ rb -> head = rb -> max - 1 ;
74+ }
75+
76+ * result = t ;
77+ return 0 ;
78+ }
79+
80+ //get the value in front of the queue
81+ int front (ringBuffer * rb ,int * result )
82+ {
83+ if (rb -> count == 0 )
84+ {
85+ return -1 ;
86+ }
87+
88+ * result = rb -> arr [rb -> head ];
89+ return 0 ;
90+ }
91+
92+ int isEmpty (ringBuffer * rb )
93+ {
94+ return rb -> count == 0 ?1 :0 ;
95+ }
96+
97+ int size (ringBuffer * rb )
98+ {
99+ return rb -> count ;
100+ }
101+
102+ //basic display for the queue
103+ void display (ringBuffer * rb )
104+ {
105+ if (rb -> count == 0 )
106+ {
107+ printf ("Empty Ring Buffer\n" );
108+ return ;
109+ }
110+
111+ printf ("\nQueue: " );
112+
113+ int c = rb -> head ;
114+ int count = rb -> count ;
115+ while (count > 0 )
116+ {
117+ printf ("%d, " ,rb -> arr [c ]);
118+ c -- ;
119+ if (c < 0 )
120+ {
121+ c = rb -> max - 1 ;
122+ }
123+ count -- ;
124+ }
125+
126+ printf ("\n" );
127+ }
128+
129+
You can’t perform that action at this time.
0 commit comments