From b724fb5a781435ca81a985dad2aaea4857471351 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Mon, 24 Feb 2025 23:03:13 -0500 Subject: [PATCH] adding stack implementation --- lectures/14_stacks_queues/README.md | 4 +++ lectures/14_stacks_queues/stack.h | 43 ++++++++++++++++++++++++ lectures/14_stacks_queues/stack_test.cpp | 26 ++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 lectures/14_stacks_queues/stack.h create mode 100644 lectures/14_stacks_queues/stack_test.cpp diff --git a/lectures/14_stacks_queues/README.md b/lectures/14_stacks_queues/README.md index 6e1f877..e3375f1 100644 --- a/lectures/14_stacks_queues/README.md +++ b/lectures/14_stacks_queues/README.md @@ -203,6 +203,10 @@ int main() { You can compile and run this above [program](stack.cpp). +### 14.1.3 Stack Implementation + +We have the stack implementation and test code here: [stack.h](stack.h), [stack_test.cpp](stack_test.cpp). + ## 14.2 Additional STL Container Classes: Queues - A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. diff --git a/lectures/14_stacks_queues/stack.h b/lectures/14_stacks_queues/stack.h new file mode 100644 index 0000000..2b6133c --- /dev/null +++ b/lectures/14_stacks_queues/stack.h @@ -0,0 +1,43 @@ +#include +#include + +template +class Stack { +private: + std::vector data; // Vector to store the stack elements + +public: + // Push element onto the stack + void push(const T& value) { + data.push_back(value); + } + + // Pop element from the stack + void pop() { + if (!empty()) { + data.pop_back(); + } else { + std::cout << "Stack is empty, cannot pop!" << std::endl; + } + } + + // Get the top element of the stack + int top() { + if (!empty()) { + return data.back(); + } else { + std::cout << "Stack is empty!" << std::endl; + return -1; // Or handle as needed + } + } + + // Check if the stack is empty + bool empty() { + return data.empty(); + } + + // Get the size of the stack + int size() { + return data.size(); + } +}; diff --git a/lectures/14_stacks_queues/stack_test.cpp b/lectures/14_stacks_queues/stack_test.cpp new file mode 100644 index 0000000..b0c1c04 --- /dev/null +++ b/lectures/14_stacks_queues/stack_test.cpp @@ -0,0 +1,26 @@ +#include +#include "stack.h" + +int main() { + Stack myStack; + + myStack.push(10); + myStack.push(20); + myStack.push(30); + myStack.push(40); + myStack.push(50); + + std::cout << "Size of stack: " << myStack.size() << std::endl; + std::cout << "Top element: " << myStack.top() << std::endl; + + if (!myStack.empty()) { + std::cout << "Stack is not empty" << std::endl; + } else { + std::cout << "Stack is empty" << std::endl; + } + + myStack.pop(); + std::cout << "Top element after pop: " << myStack.top() << std::endl; + + return 0; +}