Binary Search Tree (C++)
Loading...
Searching...
No Matches
Stack Class Reference

Represents an explicit stack used to support non-recursive tree operations. More...

#include <Stack.h>

Public Member Functions

 Stack ()
 Constructs an empty Stack.
 ~Stack ()
 Destroys the Stack.
void push (Node *n)
 Pushes a node onto the stack.
Nodepop ()
 Removes and returns the node at the top of the stack.
bool isEmpty () const
 Checks whether the stack is empty.

Detailed Description

Represents an explicit stack used to support non-recursive tree operations.

The Stack class implements a simple stack structure composed of node pointers. It is used to support traversal and deletion operations within a binary search tree, including non-recursive in-order traversal and tree destruction.

The Stack does not assume ownership of the tree nodes it stores; it manages only the stack nodes required to support these operations.

Supported operations include:

  • push(): Adds a node pointer to the top of the stack.
  • pop(): Removes and returns the top node pointer.
  • isEmpty(): Checks whether the stack is empty.

Definition at line 65 of file Stack.h.

Constructor & Destructor Documentation

◆ Stack()

Stack::Stack ( )
inline

Constructs an empty Stack.

Note
Initializes the stack with its top pointer set to nullptr.

Definition at line 71 of file Stack.h.

71: top(nullptr) {}

◆ ~Stack()

Stack::~Stack ( )

Destroys the Stack.

Destroys the stack by removing all remaining nodes.

Definition at line 21 of file Stack.cpp.

21 {
22 // Remove all nodes from top to bottom.
23 while (!isEmpty()) {
24 pop();
25 }
26}
Node * pop()
Removes and returns the node at the top of the stack.
Definition Stack.cpp:40
bool isEmpty() const
Checks whether the stack is empty.
Definition Stack.cpp:52

Member Function Documentation

◆ isEmpty()

bool Stack::isEmpty ( ) const

Checks whether the stack is empty.

Returns
True if the stack contains no elements.

Determines whether the stack has any elements.

Definition at line 52 of file Stack.cpp.

52 {
53 return top == nullptr;
54}

◆ pop()

Node * Stack::pop ( )

Removes and returns the node at the top of the stack.

Returns
Pointer to the node removed from the stack.

Pops a node off the stack and returns the stored tree node pointer.

Definition at line 40 of file Stack.cpp.

40 {
41 if (!top) return nullptr;
42 StackNode* temp = top;
43 Node* result = temp->data;
44 top = top->next;
45 delete temp;
46 return result;
47}

◆ push()

void Stack::push ( Node * n)

Pushes a node onto the stack.

Parameters
nPointer to the Node being added to the top of the stack.

Inserts a node pointer at the top of the stack.

Definition at line 31 of file Stack.cpp.

31 {
32 StackNode* s = new StackNode(n);
33 s->next = top;
34 top = s;
35}

The documentation for this class was generated from the following files: