top

Search

C Tutorial

.

UpGrad

C Tutorial

Stack Using Linked List in C

Overview

It is an organized group of components that enables push and pop as its two primary activities. This article will discuss the idea of a stack and how it may be implemented in the C programming language using a linked list. In addition to delving into the specifics of push() and pop() actions, we'll walk you through the process of creating a stack from scratch using a linked list. There will also be a discussion of actual instances of stack utilization, a conclusion, and commonly asked questions

Introduction

A stack, for the most part, alluded to as the "head" of the stack in registering, is a straight information structure that just empowers pieces to be added and removed from the top. The Rearward In-First-Out (LIFO) rule, which expresses that the last piece added to the stack is the first erased, is utilized to coordinate the stack. This conduct might be contrasted with a heap of books, with the top book being the most noticeable and open, and the volumes underneath being hidden and just accessible after the top book has been taken out.

What is a Stack?

In computer science, a stack is a fundamental data structure that follows the Last-In-First-Out (LIFO) principle. The top is the only end from which components can be added or deleted since it is an ordered set of parts. The opposite end is referred to as the base or bottom of the stack. 

The two main things the stack performs are push and pop. Pushing and popping are terms used to describe adding and removing elements from a stack, respectively.

Because only the most recent item has been added or deleted, these actions allow the stack to preserve a precise order of its constituents. 

Consider a stack of books to understand what a stack looks like. The top book is the one that gets added to the stack, and the top book is the only one that can be taken out. Books below the top cannot be removed or accessed until the books on top have been done so.

Operations performed on Stack

Stacks support various operations that allow efficient manipulation of elements. The primary operations performed on a stack are as follows: 

Push: Adding an element to the stack's top with this action. All other items are moved one place downward, with the newly added element rising to the top.

Pop: This operation removes the topmost element from the stack. The element that was previously below the removed element becomes the new top. 

Peek (or Top): This operation retrieves the value of the topmost element without removing it. 

IsEmpty: This operation checks if the stack is empty or not. It returns a Boolean value indicating whether the stack contains any elements. 

IsFull: This operation checks if the stack is full or not (applicable in case of a fixed-capacity stack). 

How to push() elements in the stack using a linked list in C

Implementing a stack using a linked list in C involves creating a node structure to hold the data and the reference to the next node. The steps to push an element onto the stack using a linked list are as follows: 

  • Create a new node. 
  • Assign the value to the data field of the node. 
  • Set the next field of the node to the current top. 
  • Update the top to point to the new node.

How to pop() elements from the stack using a linked list in C

Using a linked list, do the following operations to remove an element from the top of the stack: 

  • Verify the stack's emptiness. Display an error message if it's empty. 
  • Make a temporary pointer and put the current top's value in it. 
  • Update the top to point to the next node in the stack. 
  • Free the memory occupied by the temporary pointer. 
  • Optionally, return the value of the popped element.

Program to implement Stack using Linked List in C language

Here's an example program that demonstrates the implementation of a stack using a linked list in the C language: 

C Copy code 

// Include necessary headers 
// Define the structure of a stack node 
struct Node { 
    int data; 
    struct Node* next; 
};
// Function to create a new node 
struct Node* createNode(int data) { 
    struct Node* newNode = (struct Node*)malloc(size of(struct Node)); 
    newNode->data = data; 
    newNode->next = NULL; 
    return newNode; 
}
// Function to check if the stack is empty 
int isEmpty(struct Node* top) { 
    return top == NULL; 
}
// Function to push an element onto the stack 
void push(struct Node** top, int data) { 
    struct Node* newNode = createNode(data); 
    newNode->next = *top; 
    *top = newNode; 
    printf("%d pushed to the stack.\n", data); 
} 
// Function to pop an element from the stack 
int pop(struct Node** top) { 
    if (isEmpty(*top)) { 
        printf("Stack underflow!\n"); 
        return INT_MIN; 
    } 
    struct Node* temp = *top; 
    int popped = temp->data; 
    *top = (*top)->next; 
    free(temp); 
    return popped; 
}
// Function to display the stack 
void displayStack(struct Node* top) { 
    if (isEmpty(top)) { 
        printf("Stack is empty!\n"); 
        return; 
    } 
    struct Node* current = top; 
    printf("Stack: "); 
    while (current != NULL) { 
        printf("%d ", current->data); 
        current = current->next; 
    } 
    printf("\n"); 
}
// Main function 
int main() { 
    struct Node* top = NULL; 
    push(&top, 10); 
    push(&top, 20); 
    push(&top, 30); 
    displayStack(top); 
    printf("%d popped from the stack.\n", pop(&top)); 
    displayStack(top); 
    return 0; 
}

Real-time examples of stack

Stacks find applications in various real-life scenarios. Here are a few examples: 

Function Call Stack: In computer languages, function calls are tracked using a stack. The stack is where variables and return addresses are kept when a function is called. The stack is popped to go back to the prior function when the function has finished running.

Undo-Redo Functionality: Many applications provide the ability to undo and redo actions. Stacks can be used to store the history of actions, allowing users to reverse or repeat their actions sequentially. 

Browser History: To keep track of previously visited websites, web browsers employ a stack-like structure. A new page is added to the stack each time a user views a new page. By removing items from the stack, the user may go back to earlier pages.  

Conclusion

A significant information structure in software engineering that sticks to the Rearward In-First-Out (LIFO) idea is the stack. Push and pop tasks might be done successfully in the C programming language by executing a stack utilizing a connected rundown. The core ideas of stacks were addressed in this article, along with an explanation of the push() and pop() procedures and a complete program demonstrating how to create a stack using a linked list. Developers may use stacks to tackle a variety of issues by comprehending how they work and how to apply them.

FAQs: 

1. What are the advantages of using a linked list to implement a stack? 

Using a linked list for implementing a stack offers several advantages. It, first of all, empowers the dynamic memory portion, permitting the stack to extend or contract as required. This flexibility is particularly useful when there is no drawn line on the number of pieces in the stack. Moreover, utilizing a connected rundown is proficient for adding and eliminating things from the highest point of the stack since it just includes changing a few pointers, instead of a cluster-based approach where moving components might be vital.

2. Can a stack implemented using a linked list have a variable size? 

It is true that utilizing a linked list to create a stack has the advantage of allowing for variable size. A connected rundown may powerfully dispense memory for new hubs when components are put onto the stack, not like a cluster-based stack, which has a proper cutoff. Because of its capacity to powerfully change by the number of things it incorporates, the stack is more versatile in certifiable situations.

3. How does the push operation work in a stack implemented with a linked list? 

The push operation in a linked list-based stack involves creating a new node, assigning the value to the node's data field, and updating the necessary pointers. The new node becomes the new top of the stack, with its next pointer pointing to the previous top element. This operation has a time complexity of O(1) since it only requires a few pointer updates. 

4. What happens if we try to pop an element from an empty stack implemented with a linked list? 

A stack underflow, also known as popping an element from an empty stack, causes an error situation. Before attempting to conduct the pop action, it is imperative to verify that the stack is empty. To prevent unexpected program behavior, an appropriate error message should be printed or handled if the stack is empty.

5. Can a linked list-based stack implementation handle elements of different data types? 

A linked list-based stack can accommodate elements of many data types, hence the answer is yes. The desired data type can be added as a data field to the node structure. Due to its adaptability, the stack may store and process objects of many data kinds, including characters, strings, numbers, and even user-defined data structures.

Leave a Reply

Your email address will not be published. Required fields are marked *