I have implemented my stack based on a doubly linked list. The code is tested and works; however, I am interested in any improvement ideas.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
//---------------------Stack---------------------
typedef struct Stack {
int size;
Node* head;
Node* tail;
int top;
} Stack;
const Stack stack_init = { .size = 0, .head = NULL, .tail = NULL, .top = -1 };
Node* create_node(int elm) {
Node* node = malloc(sizeof * node);
if (!node) return node;
node->data = elm;
node->prev = NULL;
node->next = NULL;
return node;
}
int is_empty_s(Stack *s) {
return s->tail == NULL;
}
void push(Stack *s, int elm) {
Node* updated_head = create_node(elm);
if (!s->head) {
s->head = updated_head;
s->tail = s->head;
} else {
updated_head->next = s->head;
s->head->prev = updated_head;
s->head = updated_head;
}
s->size++;
s->top = s->head->data;
}
int pop(Stack *s) {
if (!is_empty_s(s)) {
Node* node = s->head;
int elm = node->data;
s->head = s->head->next;
if (s->head) {
s->head->prev = NULL;
s->top = s->head->data;
}
else {
s->tail = NULL;
s->top = -1;
}
s->size--;
free(node);
return elm;
}
return -111; //assuming it -111 won't be in the stack
}
int top(Stack *s) {
return s->top;
}
void clear_s(Stack *s) {
while (s->tail)
pop(s);
}
void reverse_s(Stack *s) { //iterative
Stack *s2 = malloc(sizeof *s2);
*s2 = stack_init;
while (s->tail)
push(s2, pop(s));
s->head = s2->head;
}
void print_s(Stack *s) {
for(Node* trav = s->head; trav != NULL; trav = trav->next)
printf("%d ", trav->data);
printf("\n");
}
int main() {
Stack s1 = stack_init;
push(&s1, 5);
push(&s1, 4);
print_s(&s1);
reverse_s(&s1);
print_s(&s1);
return 0;
}
reverse_s(Stack *s)
? \$\endgroup\$