Unit2 Solutions
Unit2 Solutions
Stacks
2. How can you implement a stack using arrays and linked lists?
Implementation of a stack:
- **Using Arrays:**
1. Use a fixed-size array to store elements.
2. Maintain a variable `top` to track the index of the top element.
3. Push operation: Increment `top` and add element.
4. Pop operation: Remove element and decrement `top`.
Example in C:
```c
int evaluatePostfix(char* expr) {
Stack stack = createStack();
for (int i = 0; expr[i]; i++) {
if (isdigit(expr[i])) {
push(stack, expr[i] - '0');
} else {
int b = pop(stack);
int a = pop(stack);
switch (expr[i]) {
case '+': push(stack, a + b); break;
case '-': push(stack, a - b); break;
case '*': push(stack, a * b); break;
case '/': push(stack, a / b); break;
}
}
}
return pop(stack);
}
```
Queues
Example:
```c
void enqueue(Stack* stack1, int x) {
push(stack1, x);
}
int dequeue(Stack* stack1, Stack* stack2) {
if (isEmpty(stack2)) {
while (!isEmpty(stack1)) {
push(stack2, pop(stack1));
}
}
return pop(stack2);
}
```