C stacks
Created By: chatGPT
A stack is a fundamental data structure that follows the Last In, First Out (LIFO) principle. This means that the most recently added element is the first one to be removed. In C, stacks can be implemented using arrays or linked lists. Here’s how you can create a simple stack using an array.
#define MAX 100
struct Stack {
int top;
int items[MAX];
};
void initStack(struct Stack *s) {
s->top = -1;
}
Next, we need to implement the push operation, which adds an element to the top of the stack. Before adding, we should check if the stack is full.
int isFull(struct Stack *s) {
return s->top == MAX - 1;
}
void push(struct Stack *s, int item) {
if (isFull(s)) {
printf("Stack Overflow\n");
return;
}
s->items[++(s->top)] = item;
}
The pop operation removes the element from the top of the stack. Similar to push, we need to first check if the stack is empty to avoid removing from an empty stack.
int isEmpty(struct Stack *s) {
return s->top == -1;
}
int pop(struct Stack *s) {
if (isEmpty(s)) {
printf("Stack Underflow\n");
return -1;
}
return s->items[(s->top)--];
}
You might also want to implement a function to peek at the top element without removing it. This helps in checking the element at the top of the stack.
int peek(struct Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
return s->items[s->top];
}
Here's a complete example that demonstrates how to use the stack operations.
int main() {
struct Stack s;
initStack(&s);
push(&s, 10);
push(&s, 20);
printf("Top element is %d\n", peek(&s));
printf("Popped element is %d\n", pop(&s));
printf("Top element after pop is %d\n", peek(&s));
return 0;
}