C/C++ Data Structures

Circular Queue

First-in, first-out processing implement करें।

Circular Queue क्या है?

Circular buffer elements shift किए बिना खाली positions reuse करता है।

महत्वपूर्ण बातें

  • Operations से पहले invariants तय करें।
  • Empty, full और allocation-failure cases संभालें।
  • Complexity और ownership साथ मापें।

देखें यह कैसे काम करता है

enqueue और dequeue करके देखें कि आइटम उसी क्रम में निकलते हैं जिसमें वे आए थे।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>

typedef struct {
    int data[4];
    int head;
    int size;
} Queue;

int push(Queue *queue, int value) {
    if (queue->size == 4) return 0;
    int tail = (queue->head + queue->size) % 4;
    queue->data[tail] = value;
    ++queue->size;
    return 1;
}

int pop(Queue *queue, int *value) {
    if (queue->size == 0) return 0;
    *value = queue->data[queue->head];
    queue->head = (queue->head + 1) % 4;
    --queue->size;
    return 1;
}

int main(void) {
    Queue queue = {{0}, 0, 0};
    int value;
    push(&queue, 7);
    push(&queue, 9);
    pop(&queue, &value);
    printf("%d\n", value);
}
अपेक्षित output
7
C++
कोड चलाएँ →
main.cpp
#include <iostream>
#include <queue>

int main() {
    std::queue<int> values;
    values.push(7);
    values.push(9);
    std::cout << values.front() << '\n';
    values.pop();
}
अपेक्षित output
7

C और C++ की तुलना

C modulo से head और size track करता है; std::queue front, push और pop देता है।

C

Structures और operations अलग, allocation स्पष्ट होता है।

C++

Classes और containers invariants और resources manage करते हैं।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • Empty और capacity boundary tests जोड़ें।
  • Cleanup लागू कर leaks जाँचें।
  • Standard container से तुलना करें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज