From c8971cb204b45e10b535444c6f11558d2f18ea2a Mon Sep 17 00:00:00 2001 From: NaiJi Date: Fri, 26 Apr 2024 17:36:29 +0400 Subject: [PATCH] 9 --- .../9. Stack.c | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 The Last Algorithms Course You'll Need/9. Stack.c diff --git a/The Last Algorithms Course You'll Need/9. Stack.c b/The Last Algorithms Course You'll Need/9. Stack.c new file mode 100644 index 0000000..ae32875 --- /dev/null +++ b/The Last Algorithms Course You'll Need/9. Stack.c @@ -0,0 +1,103 @@ +#include +#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); +}