solutions/The Last Algorithms Course .../9. Stack.c

104 lines
1.3 KiB
C
Raw Normal View History

2024-04-26 09:36:29 -04:00
#include <stdio.h>
#include "stdlib.h"
typedef int BOOL;
#define TRUE 1
#define FALSE 0
typedef struct node
{
int value;
struct node *prev;
} Node;
typedef struct
{
int value;
BOOL flag;
} ListValue;
static Node* HEAD;
static Node* TAIL;
static int LENGTH = 0;
// O(1) operation, no growth by input
BOOL push(int value)
{
Node* new_head = malloc(sizeof(Node));
if (new_head == NULL)
return FALSE;
new_head->value = value;
new_head->prev = HEAD;
if (HEAD == NULL)
TAIL = new_head;
HEAD = new_head;
++LENGTH;
return TRUE;
}
// O(1) operation, no growth by input
ListValue pop()
{
ListValue value = { 0, FALSE };
Node* iterator = HEAD;
if (iterator == NULL)
return value;
if (HEAD != TAIL)
{
HEAD = iterator->prev;
}
else
{
HEAD = NULL;
TAIL = NULL;
}
value.value = iterator->value;
value.flag = TRUE;
free(iterator);
iterator = NULL;
--LENGTH;
return value;
}
// O(1) operation, no growth by input
ListValue peek()
{
ListValue value = { 0, FALSE };
Node* iterator = HEAD;
if (iterator == NULL)
return value;
value.value = iterator->value;
value.flag = TRUE;
return value;
}
int main()
{
push(5);
push(22);
push(66);
push(122);
push(9);
printf("peek: %d\n", peek().value);
pop();
printf("peek: %d\n", peek().value);
pop();
printf("peek: %d\n", peek().value);
}