As @drescherjm suggested in the comments, you could make a static array of Node and index into that. The advantage of that is that the code only differs in the allocation function. For dynamic allocation, you would make a node with new Node
and with a static array you would use &heap[++size];
Note that if the array is global it isn't actually on the stack - it needs to be a local variable to be on the stack.
#include <iostream>
struct Node
{
long data;
Node *next;
};
Node heap[1000];
int capacity = 1000;
int size = 0;
Node *alloc()
{
// For dynamic allocation you would:
// return new Node;
// For stack allocation you would:
// return &heap[++size];
if (size >= capacity)
throw std::bad_alloc();
return &heap[size++];
}
int main()
{
Node *head = alloc();
head->data = 999;
std::cout << "head: " << head << " (value: " << head->data << ")\n";
Node *new_node = alloc();
new_node->data = 1;
head->next = new_node;
std::cout << "node: " << new_node << " (value: " << (head->next)->data << ")\n";
std::cout << "heap: " << heap << " (used/capacity: " << size << "/" << capacity << ")\n";
return 0;
}
Try it at https://onlinegdb.com/r1g-w4LKw