Stack Data Structure
Last-in, first-out operations implement करें।
Stack Data Structure क्या है?
Stack top पर काम करता है: push जोड़ता, pop हटाता और peek पढ़ता है।
महत्वपूर्ण बातें
- Operations से पहले invariants तय करें।
- Empty, full और allocation-failure cases संभालें।
- Complexity और ownership साथ मापें।
देखें यह कैसे काम करता है
push और pop करके देखें कि सबसे आख़िर में डाला गया आइटम हमेशा सबसे पहले निकलता है।
C और C++ code examples
main.c
#include <stdio.h>
typedef struct {
int data[8];
int size;
} Stack;
int push(Stack *stack, int value) {
if (stack->size == 8) return 0;
stack->data[stack->size++] = value;
return 1;
}
int pop(Stack *stack, int *value) {
if (stack->size == 0) return 0;
*value = stack->data[--stack->size];
return 1;
}
int main(void) {
Stack stack = {{0}, 0};
int value;
push(&stack, 10);
push(&stack, 20);
pop(&stack, &value);
printf("%d\n", value);
}
20
C++
main.cpp
#include <iostream>
#include <stack>
int main() {
std::stack<int> values;
values.push(10);
values.push(20);
std::cout << values.top() << '\n';
values.pop();
}
20
C और C++ की तुलना
Fixed-capacity C overflow/underflow जाँचता है; std::stack underlying container से capacity संभालता है।
C
Structures और operations अलग, allocation स्पष्ट होता है।
C++
Classes और containers invariants और resources manage करते हैं।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- Empty और capacity boundary tests जोड़ें।
- Cleanup लागू कर leaks जाँचें।
- Standard container से तुलना करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज