Queue and Stack

Queue implmentation using linked lists


A queue is a First In, First Out (FIFO) Abstract Data Type.

Anything that gets added goes to the back of the line/rear

Anything that gets removed from the Queue is taken from the “front”


Some applications

  • Network printer

  • Job scheduling by OS

  • Call center phone call queue

  • Queue of people at any service point

  • Algorithm such as BFS(breath first search)


Queue operations

  • enQueue: add a new item

  • deQueue: get and remove from the front of the Queue

  • isEmpty: determining whether the queue is empty

  • isFull : determininting whether the queue is full

  • Peek:get the element at the front without removing it


Queues can be implemented with linked lists as well as arrays.



Front = 0;
Rear = 0;

arr[Rear] = item;
Rear++;

Front++;
val = arr[Front];

For Array implementation

void EnQueue(int x)
{
if( Rear < Max_Size)
{
Queue[Rear++] = x;
printf(“Inserted“);
}
else
printf(“Full“);
}


int DeQueue()
{
if(Front==Rear)
{
printf(“Empty“);
return -9999;
}
else
return Queue[Front++];
}


//Circular implementation



// noe = number of elements
(F + noe)%size


/

// how to change nodes
rear.next = newnode;
rear = newnode;

// how to dequeue

temp = front;
front = front.next//just doing this loses the data, so need to do everything else
val = temp.data
free(temp)
return val;

//for isEmpty, check if front is pointing to null
// for isFull, it will never be full, so no need to have that






/

Stack and Stack Applications

(like chainlink implementation/yugioh reference)


LIFO(last in, first out), also an abstract data type(can search, insert, delete)


push = inserting = adding a new item

pop = deleting(getting out)(dequeue)


Top = peek = checking the most recently added item without deleting it(how high the chainlink went, ex.7, and checking that one(7))

isEmpty = if the top is null = how to determine whether a stack is empty

isFull = when a stack is full


Applications of Stack

  • Program execution(like function call/recursion)

  • Exaluating expressions// if you don’t use parenthesis, it will do it like stack(a/b + c - d*e + c - a e)(with it (a/b) + c - (d * e) + c- (a * e)

  • Undo operation(Ctrl Z)

  • Searching path in a graph

  • Validating the balance of parenthesis(and just order operations i guess??)


ex. of stack operations


Some Implementations of stack :

  1. Using global top and global array variables(don’t use global variables as much as possible, don’t like them)

  2. using struct array and variables

  3. using linked list


ex. of implmentation of stack using gloabl array variables


Balancing Parenthesis

Read the string char by char left to right,

– If you see a (, [, or {, push it on the stack

– If you see a ), ], or }, pop the stack and check whether

you got the corresponding (, [, or {

– When you reach the end, check that the stack is

empty. If it is empty, it is balanced.


Infix to Postfix


+AB => Pre-fix
AB+ => Post-fix
A+B+C => AB+C+// adding a and b, then adding that result to c
A+B*C => ABC*+// multiplying b and c, then adding that result to a

(A+B)*C => AB+C*// adding a and b, then multiplying that result to c

ABC+* // adding b and c, then multiplying that result to a




example:

4*2 +3 + 8/4 = 13

if operand(4,2,3,etc.)
   // put in postfix

if operator(+ * / -)
    if(currentOp > topOp)
        //push it to stack
    else(currentOp <= top of stack)
       // pop operatros from stack till currentOp > top
        //then push currentOp to stakc

//postfix
{4 2 * 3 + 8 4 / +} = 42*3+84/+ = 13 
// 4 times 2, add three, then 8/4, then adding 11 to 2, getting 13
// stack
{*(popped, so its gone now) +  }
{+(popped) +  }
{+ /(when done, keep popping until top is empty }
{ }

example:

5 6 + 7 * 8 9 * - // adding, then multiplying, then multipying, then finally subtracting

// 5 + 6 = 11 times 7 = 77, 8 * 9 = 72, and 77 - 72 = 5

example:

7-12 / (5-2*1)+2

//postfix
{ 7 12 5 2 1 * - / - 2 + }

//stack
//parenthesis "(" acts like a boundary
{ - / ( - * )(these four got popped(parenthesis, -, *)
{ - /(got popped, both / and - }
{+} // pop whatever else remains
{}

Evaluating from Postfix

Consider: an Empty Stack

• Read the expression from left to right

• If we encounter an operand: PUSH the

operand to the stack

• If we encounter an operator:

– Pop the two operands from the stack,

– Evaluate two operands with the operator

– Push the evaluation into the stack

• Repeat it till the end of the expression.

Other stuff

//what the evaluation looks like 
if operand => put it in POST
if operator
    if curOP > topOP
        Push curOP to stack
    else
        pop all topOp and put in Stack
        push curup to stack

if stk not empty, pop and put to post

When popping operands, the first one popped would be the second one, and the second one popped would be the first one.

Example:

4 2 × 3 + 8 4 / +

8 + 3 //pop 4 and 2 and *

11 + 8/4 // pop 8 and 3, then pop 8 and 4

11 + 2 // pop these two operands

13 // final answer


If the postFix is not just one item/empty, then it is possible that the postFix was wrong



( ( A + B ) * D ) ↑ ( E - F)

// Postfix A B + D * E F - ↑
// Stack  ↑ 
// with the rest in stack, pop when string is done

Code Implementation

//InFix to PostFix implementation
#include <stdio.h>
#include <string.h>
#define SIZE 100


int precedence(char c) {
if (c == '+' || c == '-')
return 1;
else if (c == '/' || c == '*')
return 2;
else
return -1;
}

// Stack implementation
char stack[SIZE];
int top = -1;

int isEmpty() {
return top == -1;
}

int isFull(){
return top == SIZE - 1;
}

void push(char c) {
if (isFull()){
printf("Stack overflow!\n");
return;
}
stack[++top] = c;
}

char pop() {
if(isEmpty()){
printf("Stack Underflow!\n");
return '-';
}
return stack[top--];
}

char peek() {
return stack[top];
}


void infixToPostfix(char* exp) {
int len = strlen(exp);
for (int i = 0; i < len; i++) {
char c = exp[i];
if (c >= '0' && c <= '9') { //encounter operand (numbers) - output
printf("%c", c);
}
else if (c == '(') { // opening parenthesis - just push it.
push(c);
}
else if (c == ')') { //closing parenthesis - pop everything till
empty or opening parenthesis
while (!isEmpty() && peek() != '(') {
char p = pop();
printf("%c", p);
}
if (!isEmpty())
pop(); // remove '(' ; no need to output any parenthesis
}
else { // operator (+, -, *, /, etc.)
while (!isEmpty() && peek() != '(' && precedence(peek()) >=
precedence(c)) { //if peek has higher precedence items, pop them all
char p = pop();
printf("%c", p);
}
push(c); // push the current one
}
}
while (!isEmpty()) { //pop all the remaining from the stack
char p = pop();
printf("%c", p);
}
printf("\n");
}


int main() {
char expression[] = "4*2+3+8/4";
infixToPostfix(expression);
return 0;
}

// PostFix evaluation(from postfix to a result)
#include <stdio.h>
#include <string.h> // For strlen

#define SIZE 100

int stack[SIZE];
int top = -1;

int isEmpty() {
    return top == -1;
}

int isFull(){
    return top == SIZE - 1;
}

void push(int item) {
    if (isFull()) {
        printf("Stack Overflow!\n");
        return;
    }
    stack[++top] = item;
}

int pop() {
    if (isEmpty()) {
        printf("Stack Underflow!\n");
        return -1; // Or handle error appropriately
    }
    return stack[top--];
}

int evaluate(int a, char sign, int b)
{
    if (sign == '+')
        return a + b;
    else if(sign == '-')
        return a - b;
    else if (sign == '*')
        return a * b;
    else if (sign == '/')
        return a / b;       //might want to handle division by zero if b is 0
}

int evaluatePostfix(char* expression) {
    int i;
    char ch;
    int operand1, operand2, result;

    for (i = 0; i < strlen(expression); i++) {
        ch = expression[i];

        if (ch >= '0' && ch <= '9') {
            push(ch - '0'); // operands - push it to stack (Convert char digit to int by ch - '0')
        }
        else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {    //operator - evaluate
            operand2 = pop();           //first popped item is the second operand
            operand1 = pop();           //next popped item is the first operand

            result = evaluate(operand1, ch, operand2);
            push(result);               //push it back to stack
        }
    }
    return pop(); // The final result is on top of the stack
}

int main() {
    char expression[] = "42*3+84/+";
    printf("Postfix expression: %s\n", expression);
    printf("Evaluated value: %d\n", evaluatePostfix(expression));

    char expression1[] = "231*+9-"; // Example: (2 + (3 * 1)) - 9 = -4
    printf("Postfix expression: %s\n", expression1);
    printf("Evaluated value: %d\n", evaluatePostfix(expression1));

    char expression2[] = "78+32-/"; // Example: (7+8) / (3-2) = 15
    printf("Postfix expression: %s\n", expression2);
    printf("Evaluated value: %d\n", evaluatePostfix(expression2));

    return 0;
}

/* Queue Implementation with Linked List */

#include <stdio.h>
#include <stdlib.h>
#define EMPTY -1

// Stores one node of the linked list.
struct node {
    int data;
    struct node* next;
};

// Stores our queue.
struct queue {
    struct node* front;
    struct node* back;
};

void init(struct queue* qPtr);
int enqueue(struct queue* qPtr, int val);
int dequeue(struct queue* qPtr);
int empty(struct queue* qPtr);
int peek(struct queue* qPtr);
void displayQueue(struct queue* MyQueuePtr);

int main() {
    struct queue* MyQueuePtr = (struct queue*)malloc(sizeof(struct queue));
    init(MyQueuePtr);
    int choice;
    int data;

    while (1) {
        printf("\n1. Insert element to queue \n");
        printf("2. Delete element from queue \n");
        printf("3. Display all elements of queue \n");
        printf("4. Quit \n");
        printf("Enter your choice : ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("\nWhat data you want to put in the queue?: ");
                scanf("%d", &data);
                enqueue(MyQueuePtr, data);
                displayQueue(MyQueuePtr);
                break;
            case 2:
                data = dequeue(MyQueuePtr);
                if (data != EMPTY) {
                    printf("\n%d deleted from queue\n", data);
                    displayQueue(MyQueuePtr);
                } else {
                    printf("Empty queue\n");
                }
                break;
            case 3:
                displayQueue(MyQueuePtr);
                break;
            case 4:
                exit(1);
            default:
                printf("Wrong choice \n");
        }
    }
    return 0;
}

void displayQueue(struct queue* MyQueuePtr) {
    struct node* t = MyQueuePtr->front;
    while (t) {
        printf("%d ", t->data);
        t = t->next;
    }
}

void init(struct queue* qPtr) {
    qPtr->front = NULL;
    qPtr->back = NULL;
}

int enqueue(struct queue* qPtr, int val) {
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    if (newNode == NULL)
        return 0;

    newNode->data = val;
    newNode->next = NULL;

    if (qPtr->back == NULL) {
        qPtr->front = newNode;
        qPtr->back = newNode;
    } else {
        qPtr->back->next = newNode;
        qPtr->back = newNode;
    }
    return 1;
}

int dequeue(struct queue* qPtr) {
    if (qPtr->front == NULL)
        return EMPTY;

    struct node* temp = qPtr->front;
    int val = temp->data;
    qPtr->front = qPtr->front->next;

    if (qPtr->front == NULL)
        qPtr->back = NULL;

    free(temp);
    return val;
}

int empty(struct queue* qPtr) {
    return (qPtr->front == NULL);
}

int peek(struct queue* qPtr) {
    if (qPtr->front == NULL)
        return EMPTY;
    return qPtr->front->data;
}