Explanation of the Code:
// Structure for linked list implementation of stack
struct node {
int data; // This stores the actual data
struct node *link; // This is a pointer that will point to the next node
} *top = NULL; // 'top' is a global pointer that keeps track of the top of the stack
Why Do We Need struct node *link?
Since we are using linked list for stack implementation, we need a way to connect multiple nodes together. That's why we use a pointer inside the structure.
- Each
nodewill store two things:- Data → The value that the stack holds.
- Link (Pointer) → This points to the next node in the stack.
Without this pointer, the nodes would not be connected, and we wouldn’t be able to track multiple values in the stack.
Role of top = NULL;
topis a pointer that will always point to the topmost node of the stack.- Initially,
topisNULL, meaning the stack is empty at the start. - As we push elements,
topwill always point to the most recently added element. - When we pop an element,
topwill move to the previous node.
How It Works (Step-by-Step Example):
1. Stack is empty initially
top -> NULL
(There are no elements yet.)
2. Push(10) - Insert first element
- A new node is created.
data = 10, and itslinkpoints toNULL(since this is the first node).topnow points to this node.
top -> [10 | NULL]
3. Push(20) - Insert another element
- A new node is created.
data = 20, and itslinkpoints to the previous top (which was 10).topnow points to this new node.
top -> [20 | *] -> [10 | NULL]
(* means pointing to the next node.)
4. Push(30) - Insert another element
- A new node is created.
data = 30, and itslinkpoints to the previous top (which was 20).topnow points to this new node.
top -> [30 | *] -> [20 | *] -> [10 | NULL]
5. Pop() - Remove the top element (30)
topmoves to the next node (20), and the node with30is deleted.
top -> [20 | *] -> [10 | NULL]
This process continues as we push and pop elements.
Final Thoughts
- The pointer inside
struct node(struct node *link;) is needed so that we can connect multiple nodes to form a linked list structure for the stack. tophelps us keep track of the last inserted element, making push and pop operations easy.
You understood the basics correctly! You just needed a bit more clarity on why we use the pointer and how it connects nodes to maintain the stack structure. 🚀


If you have any dough, please let me know