You are currently viewing Best Stack implementation code

Best Stack implementation code

Code for implementing Special Stack

For learning c code in more advanced form, students are advised to practice few codes related to pointer, dynamic memory allocation. For learning pointer, dynamic memory allocation you should go through this code. This is Code for implementing Special Stack

In C code practice, this Code for implementing Special Stack logic plays a very important role. So I have designed this code as easy as possible for the students. They will be able to understand each and every step very easily. 

Before going for this type of program a student should go through basics of pointer, dynamic memory allocation etc. So that they can easily go through each step with self explanation mode. 

For more code click here. For video tutorial on several topics click here

#include<stdio.h>
#include<stdlib.h>
#define max 50
typedef struct stack
{
int ar[max];
int top;
}st;

void push(st *,int);
int pop(st *);
int peek(st);

int isfull(st);
int isempty(st);
void disp(st);

void main()
{
int ch,g;
st s;
s.top=-1;
while(1)
{
printf("\n1)Push\n2)Pop\n3)Peek\n4)Disp\n5)Exit");
printf("\n Enter your choice ; ");
scanf("%d",&ch);

switch(ch)
{
case 1: if(!isfull(s))
 {
 printf("Enter the value : ");
 scanf("%d",&g);
 push(&s,g);
 }
 else
 printf("No More Space");
 break;

case 2: if(!isempty(s))
 printf("Popped value is %d",pop(&s));
 else
 printf("Nothing to display ");
 break;
case 3: if(!isempty(s))
 {
 printf("Top value is %d",peek(s));
 }
 else
 printf("Nothing to display");
 break;
case 4: if(!isempty(s))
 {
 printf("Values in the stack are : ");
 disp(s);
 }
 else
 printf("Nothing to display");
 break;
case 5: exit(0);
}
}
}

void push(st *s,int g)
{
s->ar[++s->top]=g;
}

int pop(st *s)
{
int p;
p=s->ar[s->top];
s->top--;
return p;
}
int peek(st s) { return s.ar[s.top]; } int isfull(st s) { if(s.top==max-1) return 1; else return 0; } int isempty(st s) { if(s.top==-1) return 1; else return 0; } void disp(st s) { int p=s.top; printf("\n\n"); while(p>=0) { printf("|%d|\n",s.ar[p]); p--; } }

Detail Explanation of the above code

Let’s further delve into the code line-by-line to provide a more in-depth explanation of the stack implementation using C. This will include a detailed breakdown of how each function operates, why certain checks and steps are necessary, and the overall working of the stack data structure in this context.

 1. Preprocessor Directives and Stack Definition

#include<stdio.h>
#include<stdlib.h>
#define max 50

 #include<stdio.h> : This directive includes the standard input/output library, which contains functions like `printf()` and `scanf()` used for displaying output and taking input, respectively.
#include<stdlib.h> : This directive includes the standard library, which provides functions like `exit()` for terminating the program.
#define max 50 : Defines a constant named `max` with the value `50`. This is a symbolic constant used to set the maximum size of the stack array, which helps make the code easier to maintain. If the size of the stack needs to be changed, you only need to update this value.

2. Stack Structure Definition

typedef struct stack {
int ar[max];
int top;
} st;

typedef struct stack {…} st; : Defines a new structure called `stack` and uses `typedef` to create an alias `st` for the structure, simplifying the syntax when declaring stack variables.

int ar[max]; : This is an integer array of size `max` (50). This array acts as the actual storage for the stack elements. Since it’s a fixed-size array, it limits the stack to hold a maximum of 50 elements.

int top; : This variable tracks the index of the top element in the stack. Initially, it is set to `-1` to indicate that the stack is empty.

3. Function Prototypes

void push(st *, int);
int pop(st *);
int peek(st);
int isfull(st);
int isempty(st);
void disp(st);

These are function declarations (prototypes) that inform the compiler about the functions used later in the code. Each function operates on the stack:

void push(st *, int); : Function that takes a pointer to a stack (`st *`) and an integer value. It adds the integer to the top of the stack.

int pop(st *); : Function that takes a pointer to a stack and removes the top element, returning its value.

int peek(st); : Function that takes a stack and returns the value of the top element without removing it.

 int isfull(st); : Function that checks if the stack is full. It returns `1` if full and `0` otherwise.

 int isempty(st); : Function that checks if the stack is empty. It returns `1` if empty and `0` otherwise.

void disp(st); : Function that displays all elements of the stack.

4. Main Function

void main() {
int ch, g;
st s;
s.top = -1;
`

void main() : Defines the main entry point of the program. Note that `int main()` is the standard form for defining the main function in C.

int ch, g; : Declares two integer variables:
ch : Stores the user’s menu choice.
 g : Used for input when adding values to the stack.

 st s; : Declares a stack variable `s` of type `st`, which means it’s a stack with an array `ar` and an integer `top`.

s.top = -1; : Initializes the stack by setting `top` to `-1`, indicating the stack is empty (no elements are in the stack).

 5. Menu-driven Stack Operations

while (1) {
printf(“\n1)Push\n2)Pop\n3)Peek\n4)Disp\n5)Exit”);
printf(“\n Enter your choice ; “);
scanf(“%d”, &ch);

while (1) : This loop runs indefinitely until `exit()` is called from within the loop, ensuring that the menu is displayed continuously until the user decides to exit.

printf(“\n1)Push\n2)Pop\n3)Peek\n4)Disp\n5)Exit”); : Displays the menu options to the user. Each number corresponds to a specific stack operation.

scanf(“%d”, &ch); : Reads the user’s choice and stores it in the variable `ch`.

switch (ch) {
case 1:
if (!isfull(s)) {
printf(“Enter the value : “);
scanf(“%d”, &g);
push(&s, g);
} else {
printf(“No More Space”);
}
break;

`switch (ch) : Uses the value of `ch` to determine which case block to execute based on the user’s input.

#### **Case 1: Push Operation**

– **`if (!isfull(s))`**: Calls `isfull(s)` to check if the stack is full. The `!` operator negates the result. If the stack is not full (`0`), the code inside the block is executed.

– **`scanf(“%d”, &g);`**: Prompts the user to enter an integer value that will be pushed onto the stack.

– **`push(&s, g);`**: Calls the `push()` function with the address of the stack `s` (`&s`) and the value `g`. This function adds `g` to the top of the stack.

– **`else { printf(“No More Space”); }`**: If the stack is full (`isfull()` returns `1`), it prints “No More Space” to inform the user.

“`c
case 2:
if (!isempty(s))
printf(“Popped value is %d”, pop(&s));
else
printf(“Nothing to display “);
break;
“`

#### **Case 2: Pop Operation**

– **`if (!isempty(s))`**: Checks if the stack is not empty by calling `isempty(s)`. If the stack is not empty, the code inside the block is executed.

– **`pop(&s);`**: Calls the `pop()` function with the address of the stack `s`. This function removes the top element and returns its value.

– **`printf(“Popped value is %d”, pop(&s));`**: Prints the value that was popped from the stack.

– **`else { printf(“Nothing to display”); }`**: If the stack is empty (`isempty()` returns `1`), it informs the user that there is nothing to pop.

“`c
case 3:
if (!isempty(s)) {
printf(“Top value is %d”, peek(s));
} else {
printf(“Nothing to display”);
}
break;
“`

#### **Case 3: Peek Operation**

– **`if (!isempty(s))`**: Checks if the stack is not empty. If the stack is not empty, the code inside the block is executed.

– **`peek(s);`**: Calls the `peek()` function with the stack `s`. This function returns the value of the top element without removing it.

– **`printf(“Top value is %d”, peek(s));`**: Prints the top element of the stack.

– **`else { printf(“Nothing to display”); }`**: If the stack is empty, it informs the user that there is nothing to display.

“`c
case 4:
if (!isempty(s)) {
printf(“Values in the stack are : “);
disp(s);
} else {
printf(“Nothing to display”);
}
break;
“`

#### **Case 4: Display Stack Elements**

– **`if (!isempty(s))`**: Checks if the stack is not empty. If the stack is not empty, the code inside the block is executed.

– **`disp(s);`**: Calls the `disp()` function, which prints all elements in the stack from top to bottom.

– **`else { printf(“Nothing to display”); }`**: If the stack is empty, it informs the user that there is nothing to display.

“`c
case 5:
exit(0);
}
“`

#### **Case 5: Exit**

– **`exit(0);`**: Exits the program with status `0`, indicating normal termination.

### 6. **Stack Operation Functions**

#### **Push Function**

“`c
void push(st *s, int g) {
s->ar[++s->top] = g;
}
“`

– **`void push(st *s, int g)`**: Adds an element to the stack.
– **`st *s`**: Pointer to the stack, allowing modification of the actual stack passed from the main function.
– **`int g`**: The value to be added to the stack.

– **`s->ar[++s->top] = g;`**: Performs two operations:
– **`++s->top`**: Increments `top` to point to the next available position in the array.
– **`s->ar[s->top] = g;`**: Stores

the value `g` in the newly incremented top position.

#### **Pop Function**

“`c
int pop(st *s) {
int p;
p = s->ar[s->top];
s->top–;
return p;
}
“`

– **`int pop(st *s)`**: Removes and returns the top element of the stack.
– **`st *s`**: Pointer to the stack, allowing direct modification.

– **`int p;`**: Declares a temporary variable `p` to hold the value of the top element.

– **`p = s->ar[s->top];`**: Retrieves the current top element and stores it in `p`.

– **`s->top–;`**: Decrements `top` to remove the current top element effectively.

– **`return p;`**: Returns the popped value.

#### **Peek Function**

“`c
int peek(st s) {
return s.ar[s.top];
}
“`

– **`int peek(st s)`**: Returns the top element without modifying the stack.

– **`return s.ar[s.top];`**: Accesses the top element using `s.top` and returns its value.

#### **isfull Function**

“`c
int isfull(st s) {
if (s.top == max – 1)
return 1;
else
return 0;
}
“`

– **`int isfull(st s)`**: Checks if the stack is full.

– **`if (s.top == max – 1)`**: Compares `top` with `max – 1` (49), the last valid index in the array. If `top` equals `49`, the stack is full.

– **`return 1;`**: Returns `1` if the stack is full.

– **`return 0;`**: Returns `0` if the stack is not full.

#### **isempty Function**

“`c
int isempty(st s) {
if (s.top == -1)
return 1;
else
return 0;
}
“`

– **`int isempty(st s)`**: Checks if the stack is empty.

– **`if (s.top == -1)`**: Checks if `top` is `-1`, which means the stack has no elements.

– **`return 1;`**: Returns `1` if the stack is empty.

– **`return 0;`**: Returns `0` if the stack is not empty.

#### **Display Function**

“`c
void disp(st s) {
int p = s.top;
printf(“\n\n”);
while (p >= 0) {
printf(“|%d|\n”, s.ar[p]);
p–;
}
}
“`

– **`void disp(st s)`**: Displays all elements of the stack from top to bottom.

– **`int p = s.top;`**: Initializes a temporary variable `p` to point to the current top index.

– **`while (p >= 0)`**: Loops while `p` is greater than or equal to `0`, printing each element from top to bottom.

– **`printf(“|%d|\n”, s.ar[p]);`**: Prints the current element at position `p` in the stack.

– **`p–;`**: Decrements `p` to move down the stack.

This breakdown provides a comprehensive understanding of how each component of the stack operates, emphasizing the logic behind every function, check, and manipulation of the stack elements.

Leave a Reply