0% found this document useful (0 votes)
1 views17 pages

Stack

The document provides multiple implementations of stack data structures in C, including basic operations like push, pop, and peek. It covers various applications of stacks such as reversing strings, checking for palindromes, and converting decimal numbers to binary and hexadecimal. Additionally, it includes algorithms for converting infix expressions to postfix notation using both array-based and struct-based stack implementations.

Uploaded by

acsses18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views17 pages

Stack

The document provides multiple implementations of stack data structures in C, including basic operations like push, pop, and peek. It covers various applications of stacks such as reversing strings, checking for palindromes, and converting decimal numbers to binary and hexadecimal. Additionally, it includes algorithms for converting infix expressions to postfix notation using both array-based and struct-based stack implementations.

Uploaded by

acsses18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

STACK

Implementation of stack using structure


#include <stdio.h>
struct sta
{
int max_size;
int stack[8];
int top;
} s;
int isEmpty()
{
return (s.top == -1);
}
int isFull()
{
return (s.top == s.max_size - 1);
}
int peek()
{
return s.stack[s.top];
}
int pop()
{
int data;
if (!isEmpty())
{
data = s.stack[s.top];
s.top = s.top - 1;
return data;
}
else
{
printf("Stack is empty. Could not retrieve data.\n");
return -1; // Return a sentinel value to indicate an error condition.
}
}
void push(int data)
{
if (!isFull())

Prof Swetanjali Maharana


{
s.top = s.top + 1;
s.stack[s.top] = data;
}
else
{
printf("Stack is full. Cannot insert data.\n");
}
}
int main()
{
s.max_size = 8;
s.top = -1;
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);
printf("Element at the top: %d\n", peek());
printf("Elements in the stack:\n");
while (!isEmpty())
{
int data = pop();
printf("%d\n", data);
}
printf("stack full:%s\n",isFull()?"true":"false");
printf("stack empty:%s\n",isEmpty()?"true":"false");
return 0;
}

OUTPUT
lement at the top: 15
Elements in the stack:
15
12
1
9
5
3

Prof Swetanjali Maharana


stack full:false
stack empty:true

String reverse in Stack


#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
struct Stack {
int top;
char items[MAX_SIZE];
};
void initialize(struct Stack* stack)
{
stack->top = -1;
}
int isFull(struct Stack* stack)
{
return stack->top == MAX_SIZE - 1;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
void push(struct Stack* stack, char item)
{
if (isFull(stack))
{
printf("Stack is full. Cannot push.\n");
return;
}
stack->items[++stack->top] = item;
}
char pop(struct Stack* stack)
{
if (isEmpty(stack))
{
printf("Stack is empty. Cannot pop.\n");
return '\0';
}

Prof Swetanjali Maharana


return stack->items[stack->top--];
}

void reverseString(char* str)


{
struct Stack stack;
initialize(&stack);
int len = strlen(str);
for (int i = 0; i < len; i++)
{
push(&stack, str[i]);
}
for (int i = 0; i < len; i++)
{
str[i] = pop(&stack);
}
}
int main() {
char str[] = "Hello, World!";
printf("Original String: %s\n", str);

reverseString(str);

printf("Reversed String: %s\n", str);

return 0;
}
OUTPUT
Original String: Hello, World!
Reversed String: !dlroW ,olleH

palindrome using stack


#include <stdio.h>
#include <string.h>

#define MAX_SIZE 100

struct Stack {
int top;
char items[MAX_SIZE];

Prof Swetanjali Maharana


};

void initialize(struct Stack* stack)


{
stack->top = -1;
}

int isEmpty(struct Stack* stack)


{
return stack->top == -1;
}

int isFull(struct Stack* stack)


{
return stack->top == MAX_SIZE - 1;
}

void push(struct Stack* stack, char item)


{
if (isFull(stack))
{
printf("Stack is full. Cannot push.\n");
return;
}
stack->items[++stack->top] = item;
}

char pop(struct Stack* stack)


{
if (isEmpty(stack))
{
printf("Stack is empty. Cannot pop.\n");
return '\0';
}
return stack->items[stack->top--];
}
int isPalindrome(char* str)
{
struct Stack stack;
initialize(&stack);

Prof Swetanjali Maharana


int len = strlen(str);
for (int i = 0; i < len / 2; i++)
{
push(&stack, str[i]);
}
int start = len % 2 == 0 ? len / 2 : len / 2 + 1;
for (int i = start; i < len; i++)
{
char c = pop(&stack);
if (c != str[i])
{
return 0;
}
}
return 1; // Palindrome
}
int main()
{
char str[] = "MADAM";
printf("Input String: %s\n", str);
if (isPalindrome(str))
{
printf("It's a palindrome!\n");
} else
{
printf("It's not a palindrome.\n");
}
return 0;
}

OUTPUT
Input String: MADAM
It's a palindrome!

Conversion of Decimal to Binary using Stack


#include <stdio.h>
struct sta
{
int max_size;

Prof Swetanjali Maharana


int stack[8];
int top;
} s;
int init()
{
s.max_size = 8;
s.top = -1;
}
int isEmpty()
{
return (s.top == -1);
}
int isFull()
{
return (s.top == s.max_size - 1);
}

int peek()
{
return s.stack[s.top];
}
int pop()
{
int data;
if (!isEmpty())
{
data = s.stack[s.top];
s.top = s.top - 1;
return data;
}
else
{
printf("Stack is empty. Could not retrieve data.\n");
return -1;
}
}

void push(int data)


{
if (!isFull())

Prof Swetanjali Maharana


{
s.top = s.top + 1;
s.stack[s.top] = data;
}
else
{
printf("Stack is full. Cannot insert data.\n");
}
}
int DecToBin(int d)
{
int r,x;
init();
while(d>0)
{
r=d%2;
push(r);
d=d/2;
}
while(!isEmpty())
{
x= pop();
printf("%d",x);
}
}
int main()
{
int data;
printf("Enter a number:”);
scanf("%d", &data);
DecToBin(data);
return 0;
}
OUTPUT
Enter a number:6
110

Prof Swetanjali Maharana


Conversion of decimal to hexadecimal using Stack
#include <stdio.h>
#define MAX_SIZE 100

struct Stack {
int top;
char items[MAX_SIZE];
};
void initialize(struct Stack* stack)
{
stack->top = -1;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
int isFull(struct Stack* stack)
{
return stack->top == MAX_SIZE - 1;
}
void push(struct Stack* stack, char item)
{
if (isFull(stack))
{
printf("Stack is full. Cannot push.\n");
return;
}
stack->items[++stack->top] = item;
}

char pop(struct Stack* stack)


{
if (isEmpty(stack))
{
printf("Stack is empty. Cannot pop.\n");
return '\0';
}
return stack->items[stack->top--];
}

Prof Swetanjali Maharana


void decimalToHexadecimal(int decimal)
{
struct Stack stack;
initialize(&stack);

while (decimal > 0)


{
int remainder = decimal % 16;
char hexDigit;
if (remainder < 10)
{
hexDigit = remainder + '0';
} else {
hexDigit = remainder - 10 + 'A';
}
push(&stack, hexDigit);
decimal /= 16;
}
printf("Hexadecimal representation: ");
while (!isEmpty(&stack))
{
char hexDigit = pop(&stack);
printf("%c", hexDigit);
}
printf("\n");
}
int main() {
int decimalNumber = 255; // Change this to the decimal number you want to convert
decimalToHexadecimal(decimalNumber);
return 0;
}

Prof Swetanjali Maharana


Algorithm for converting infix to postfix programs:
1. Traversing the given expression from left to right should begin.
2. Just output the scanned character if it is an operand.
3. Else
o If the operand's precedence is greater than the operator's precedence in
the stack (or the stack is empty or has'('), then push the operator into the
stack.
o Else, Any operator with more or equal precedence than the traversed
operator are popped. Push this scanned operator after you pop them.
(Stop and push the scanned operator on the stack if we encounter a
parenthesis during popping.)
4. Push the scanned character to the stack if it is a '('.
5. If the scanned character is a ')', pop the stack and output it until another '('
appears, then eliminate both the parentheses.
6. Steps 2 through 6 should now be repeated until the entire infix, i.e. entire
characters, is scanned.
7. Printing results
8. Pop and print until the stack is not empty.

Conversion of Infix to Postfix Using an Array-Based Stack

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
char stk[20];
int top = -1;
int isEmpty()
{
return top == -1;
}
int isFull()
{
return top == MAX - 1;
}
char peek()

Prof Swetanjali Maharana


{
return stk[top];
}
char pop()
{
if(isEmpty())
return -1;

char ch = stk[top];
top--;
return(ch);
}
void push(char oper)
{
if(isFull())
printf("Stack Full!!!!");

else{
top++;
stk[top] = oper;
}
}
int checkIfOperand(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
int precedence(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;
case '^':
return 3;
}

Prof Swetanjali Maharana


return -1;
}
int covertInfixToPostfix(char* expression)
{
int i, j;
for (i = 0, j = -1; expression[i]; ++i)
{
if (checkIfOperand(expression[i]))
expression[++j] = expression[i];
else if (expression[i] == '(')
push(expression[i]);
else if (expression[i] == ')')
{
while (!isEmpty() && peek() != '(')
expression[++j] = pop();
if (!isEmpty() && peek() != '(')
return -1;
else
pop();
}
else
{
while (!isEmpty() && precedence(expression[i]) <= precedence(peek()))
expression[++j] = pop();
push(expression[i]);
}

}
while (!isEmpty())
expression[++j] = pop();
expression[++j] = '\0';
printf( "%s", expression);
}
int main()
{
char expression[] = "((x+(y*z))-w)";
covertInfixToPostfix(expression);
return 0;
}

Prof Swetanjali Maharana


Output
xyz*+w-

Conversion of Infix to Postfix Using a Struct-Based Stack


#include<stdio.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>

struct Stack {
int top;
int maxSize;
int* array;
};
struct Stack* create(int max)
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack -> maxSize = max;
stack -> top = -1;
stack -> array = (int*)malloc(stack -> maxSize * sizeof(int));
return stack;
}
int isFull(struct Stack* stack)
{
if(stack -> top == stack -> maxSize - 1)
{
printf("Will not be able to push maxSize reached\n");
}
return stack -> top == stack -> maxSize - 1;
}

int isEmpty(struct Stack* stack)


{
return stack -> top == -1;
}

void push(struct Stack* stack, int item)


{
if (isFull(stack))

Prof Swetanjali Maharana


return;
stack -> array[++stack -> top] = item;
}

int pop(struct Stack* stack)


{
if (isEmpty(stack))
return INT_MIN;
return stack -> array[stack -> top--];
}

int peek(struct Stack* stack)


{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}

int checkIfOperand(char ch)


{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
int precedence(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}

Prof Swetanjali Maharana


int covertInfixToPostfix(char* expression)
{
int i, j;

struct Stack* stack = create(strlen(expression));


if(!stack)
return -1 ;

for (i = 0, j = -1; expression[i]; ++i)


{
if (checkIfOperand(expression[i]))
expression[++j] = expression[i];

else if (expression[i] == '(')


push(stack, expression[i]);

else if (expression[i] == ')')


{
while (!isEmpty(stack) && peek(stack) != '(')
expression[++j] = pop(stack);
if (!isEmpty(stack) && peek(stack) != '(')
return -1;
else
pop(stack);
}
else
{
while (!isEmpty(stack) && precedence(expression[i]) <= precedence(peek(stack)))

expression[++j] = pop(stack);
push(stack, expression[i]);
}

while (!isEmpty(stack))
expression[++j] = pop(stack);

expression[++j] = '\0';
printf( "%s", expression);

Prof Swetanjali Maharana


}

int main()
{
char expression[] = "((x+(y*z))-w)";
covertInfixToPostfix(expression);
return 0;
}

Output
xyz*+w-

Prof Swetanjali Maharana

You might also like