Implementation of a stack

    by nikoo28

    An implementation of stack is similar to that of a Linked List. We will try to discuss the basic operations in a stack discussed in this post.

    MAIN OPERATIONS ON A STACK:-

    • push( int ) :- Inserts a data into the stack
    • pop :- Returns the topmost data from the stack

    AUXILIARY OPERATIONS ON A STACK

    • int Top( ) :- returns the topmost element on the stack
    • int Size( ) :- returns the total size of the stack
    • int isStackEmpty( ) :- returns true if the stack is empty

    The data structure for a stack can be made as the same as that of a single Linked List. We need a node with a next element.

    struct stackNode
    {
        int data;
        struct stackNode * next;
    };
    

    Now we need to define the basic function of pushing a node in the stack. A PUSH operation, adds a new node in the stack and points the TOP of the stack to this new node.

    // defining the generic function to PUSH an element into the stack
    struct stackNode * push(struct stackNode * top, int element)
    {
        //creating a temporary node and assigning the element to be PUSHED
        struct stackNode * temp = (struct stackNode *)malloc(sizeof(struct stackNode));
        temp -> data = element;
    
        // we need to point the NEXT of this node to the previous TOP
        temp -> next = top;
    
        // we need to update the TOP node and then return it
        // we can simply return the 'temp' node as it points to the new TOP node.
        return temp;
    }
    

    Now let us define a function to check if the stack is empty. A stack is empty, if the top node points to a NULL location

    // defining a function to check if a stack is empty
    int isStackEmpty(struct stackNode * top)
    {
        if(top == NULL)
            return 1;
        else
            return 0;
    }
    

    Now to define the POP function. To define the POP function, we must check if the stack is empty or not. If the stack is empty, that means we cannot POP any value and it is a case of stack underflow. However, if the stack is not empty, we simply print the TOP value and delete the top node.

    // defining a function to pop an element from a stack
    struct stackNode * pop(struct stackNode * top)
    {
        // check if the stack is empty
        if(isStackEmpty(top))
        {
            printf("STACK IS EMPTY...Stack underflow");
            return NULL;
        }
        else
        {
            printf("POP element = %d",top -> data);
    
            // we need to delete the top and move to the next element.
    
            struct stackNode * temp = top;
    
            // move to the next node
            top = top -> next;
    
            // delete the original top
            free(temp);
    
            // return the new top
            return top;
        }
    }
    

    The last function to get the number of elements in the stack is same as calculating the length of a single Linked List.

    // function to get the size of the stack
    int getStackSize(struct stackNode * top)
    {
        int count = 0;
        while(top)
        {
            count++;
            top = top -> next;
        }
        return count;
    }
    

    These were the basic functions used in implementing a stack and being generic functions can be used anytime we need to implement stacks. Here is a working demo of the code that utilizes all the above function. Use your favorite editor to edit it. (gEdit, vim, notepad++)

    2 comments
    0 FacebookTwitterLinkedinWhatsappEmail
  • MiscTheory

    What is Segmentation Fault?

    by nikoo28
    3 minutes read

    From Wikipedia: A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system). Segmentation is one approach to memory management and protection in the operating system. It has been superseded by paging for most purposes, but much of the terminology of segmentation is still used, “segmentation fault” being an example. …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: You are given the head pointer to 2 single Linked Lists, and both of the lists converge at a certain point and then advance forward. We need to find the address of the node, at which both of the Linked Lists meet. Input: 4 -> 8 -> 15 ->                               42 -> 99     16 -> 23 -> Output: 42 Suppose there are two single Linked Lists both of which intersect at some point and become a single Linked list. The head or start pointer of both the lists …

    1 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    How to generate a random number in C?

    by nikoo28
    1 minutes read

    This is one of the method, not everyone is aware of in C. To generate a random number, C itself provides us a method srand(). We can use it in this way. #include <stdio.h> #include <time.h> int main(void) { srand(time(NULL)); int r = rand(); printf("Random number = %d", r); return 0; } NOTE: The function srand(time(NULL)) can only be called once in the program.

    0 FacebookTwitterLinkedinWhatsappEmail
  • Many of us must have heard of the clause “Real Programmers code in C” and it is faster than any other language because “it is close to the machine“. What is so special about this language that makes it different from any other language. Let us try to explore this answer to some extent. There isn’t much that’s special about C. That’s one of the reasons why it’s fast. Newer languages which have support for garbage collection, dynamic typing and other facilities which make it easier for the programmer to …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Linked List

    Copy an entire Linked List.

    by nikoo28
    2 minutes read

    Copying an entire Linked List, means allocating new memory and copying all the data to the new location. This requires traversing each node and copying its data to a new location, keeping the original data intact. #include<stdio.h> struct node { int data; struct node * next; }; // implementing a function to copy a Linked List struct node * copyList(struct node * head) { // creating a new variable as a list struct node * list2 = (struct node *)malloc(sizeof(struct node)); //creating a temporary variable to traverse the new list …

    1 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More