Created: 2023-09-29 18:50
Status: #concept
Subject: Programming
Tags: C Data Structure Queue
Stack
An array but the only elements we can read or mutate are the ones at the top of the stack.
"First in, last out" because new items are added on top of old ones.
Implementations
#define MAX 10
- Arrays
struct Stack
{
char data[MAX];
int top;
};
typedef struct node {
char data;
struct node *next;
} *Node;
struct Stack {
Node topPtr;
int length;
};
Common Operations
/**
* @brief Adds the specified element to the top of the stack.
*
* @param s a pointer to the Stack object (struct Stack *)
* @param ch the element to add to the stack
*/
void push(Stack s, char elem) {
// checks if there is available space to insert
if (s->length < MAX) {
Node newNode = (Node)malloc(sizeof(struct node));
if (newNode != NULL) {
newNode->data = elem;
// set the link of newNode to the topPtr
newNode->next = s->topPtr;
// set topPtr to newNode
s->topPtr = newNode;
}
s->length++;
}
}
/**
* @brief Removes the element at the top of the stack.
*
* @param s a pointer to the Stack object (struct Stack *)
*/
void pop(Stack s) {
// checks if there is a node to delete
if (s->topPtr != NULL) {
// initialize temp to topPtr
Node temp = s->topPtr;
// set topPtr to topPtr link
s->topPtr = s->topPtr->next;
// dealloctes temp
free(temp);
s->length--;
}
}
/**
* @brief Returns the element at the top of the stack, otherwise ('\0') if the stack is empty.
*
* @param s a pointer to the Stack object (struct Stack *)
* @return char
*/
char top(Stack s) {
return (s->topPtr == NULL) ? '\0' : s->topPtr->data;
}