Stack Data Structure
Stack top पर काम करता है: push जोड़ता, pop हटाता और peek पढ़ता है।
Stack Data Structure क्या है?
Stack top पर काम करता है: push जोड़ता, pop हटाता और peek पढ़ता है।
Last-in, first-out operations implement करें।
महत्वपूर्ण बातें
- Operations से पहले invariants तय करें।
- Empty, full और allocation-failure cases संभालें।
- Complexity और ownership साथ मापें।
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 से तुलना करें।