Showing posts with label Data Structures. Show all posts
Showing posts with label Data Structures. Show all posts

Monday, 29 February 2016

Data Structures - Infix to Postfix Conversion - Cpp


In this post we convert an infix expression to postfix expression using stack data structure .

Generally an infix expression is a normal expression where operators are present in between the operands ex : A + B * C and  its postfix  notation is represented as ABC*+


An infix expression is converted into its postfix notation as follows :

  • Create an empty Stack for pushing and poping operators and a string for storing result
  • First scan the infix exppression from left to right if there is no exponential operator , if there is an exponential operator scan the infix expression from right to left.
  • If an operand is encountered add it to the result string
  • If a left parenthesis is encountered push it to the stack
  • If a right parenthesis is encountered pop the stack until its corresponding left parenthesis is removed and append each operator to the result string  
  • If an operator is encountered push it to the stack if the encountered operator is of lower precedence that the stack top element and pop all elements with higher or equal precedence and add to result string.
  • Check if there are any elements in the stack and pop them out and add to the result string.


Download code

PROGRAM :

    #include<iostream>
    #include<stack>
    #include<string>

    using namespace std;
    string InfixToPostfix(string expression);
    int HasHigherPrecedence(char operator1, char operator2);
    bool IsOperator(char C);
    bool IsOperand(char C);

    int main()
    {
        string expression;
        cout<<"Enter Infix Expression: \t";
        getline(cin,expression);
        string postfix = InfixToPostfix(expression);
        cout<<"Postfix expression = \t"<<postfix<<"\n";
        return 0;
    }
    string InfixToPostfix(string expression)
    {

        stack<char> S;
        string postfix = "";
        for(int i = 0; i< expression.length(); i++)
        {
        if(expression[i] == ' ' || expression[i] == ',')
            continue;
        else if(IsOperator(expression[i]))
        {
            while(!S.empty() && S.top() != '(' && HasHigherPrecedence(S.top(),expression[i]))
            {
                postfix+= S.top();
                S.pop();
            }
            S.push(expression[i]);
        }
        else if(IsOperand(expression[i]))
        {
            postfix +=expression[i];
        }

        else if (expression[i] == '(')
        {
            S.push(expression[i]);
        }

        else if(expression[i] == ')')
        {
            while(!S.empty() && S.top() !=  '(')
            {
                postfix += S.top();
                S.pop();
            }
            S.pop();
        }
        }

        while(!S.empty())
        {
        postfix += S.top();
        S.pop();
        }

        return postfix;
    }
    bool IsOperand(char C)
    {
        if(C >= '0' && C <= '9') return true;
        if(C >= 'a' && C <= 'z') return true;
        if(C >= 'A' && C <= 'Z') return true;
        return false;
    }
    bool IsOperator(char C)
    {
        if(C == '+' || C == '-' || C == '*' || C == '/' || C== '^')
        return true;
        return false;
    }
    int IsRightAssociative(char op)
    {
        if(op == '^')
        return true;
        return false;
    }
    bool IsLeftParenthesis(char ch)
    {
        if (ch == '(')
        return true;
        return false;
    }
    bool IsRightParenthesis(char ch)
    {
        if (ch == ')')
        return true;
        return false;
    }
    int GetOperatorWeight(char op)
    {
        int weight = -1;
        switch(op)
        {
        case '+':
        case '-':
        weight = 1;
        break;
        case '*':
        case '/':
        weight = 2;
        break;
        case '^':
        weight = 3;
        break;
        }
        return weight;
    }
    int HasHigherPrecedence(char op1, char op2)
    {
        int op1Weight = GetOperatorWeight(op1);
        int op2Weight = GetOperatorWeight(op2);
        if(op1Weight == op2Weight)
        {
        if(IsRightAssociative(op1))
            return false;
        else
            return true;
        }
        return op1Weight > op2Weight ?  true: false;
    }
Download code

OUTPUT :

Cpp - Data Structures - Infix to Postfix 

Cpp - Data Structures - Infix to Postfix 

Cpp - Data Structures - Infix to Postfix 

Thursday, 25 February 2016

Data Structures - Java Program to implement Linked List Operations - Insert , Delete , Update , Display

Linked List is another data structure consisting of group of nodes which together represent a sequence. Each node has two parts one for the value and other for link to the next node.
Linked lists allows dynamic memory allocation.

Singly-linked-list.svg
A singly linked list whose nodes contain two fields: an integer value and a link to the next node


Some of the operations in a linked list are :

  • Insertion into the list
  • Deletion from the list
  • Updation of the value
  • Display the list




Download code

PROGRAM :

package mycodingcorner;

    import java.util.Scanner;

    class Node {
     protected int data;
     protected Node link;

     public Node() {
      link = null;
      data = 0;
     }

     public Node(int d, Node n) {
      data = d;
      link = n;
     }

     public void setLink(Node n) {
      link = n;
     }

     public void setData(int d) {
      data = d;
     }

     public Node getLink() {
      return link;
     }

     public int getData() {
      return data;
     }
    }

    class LL {
     protected Node start;
     protected Node end;
     public int size;

     public LL() {
      start = null;
      end = null;
      size = 0;
     }

     public void insertAtStart(int val) {
      Node nptr = new Node(val, null);
      size++;
      if (start == null) {
       start = nptr;
       end = start;
      } else {
       nptr.setLink(start);
       start = nptr;
      }
     }

     public void insertAtEnd(int val) {
      Node nptr = new Node(val, null);
      size++;
      if (start == null) {
       start = nptr;
       end = start;
      } else {
       end.setLink(nptr);
       end = nptr;
      }
     }

     public void insertAtPos(int val, int pos) {
      Node nptr = new Node(val, null);
      Node ptr = start;
      pos = pos - 1;
      for (int i = 1; i < size; i++) {
       if (i == pos) {
        Node tmp = ptr.getLink();
        ptr.setLink(nptr);
        nptr.setLink(tmp);
        break;
       }
       ptr = ptr.getLink();
      }
      size++;
     }

     public void deleteAtPos(int pos) {
      if (pos == 1) {
       start = start.getLink();
       size--;
       return;
      }
      if (pos == size) {
       Node s = start;
       Node t = start;
       while (s != end) {
        t = s;
        s = s.getLink();
       }
       end = t;
       end.setLink(null);
       size--;
       return;
      }
      Node ptr = start;
      pos = pos - 1;
      for (int i = 1; i < size - 1; i++) {
       if (i == pos) {
        Node tmp = ptr.getLink();
        tmp = tmp.getLink();
        ptr.setLink(tmp);
        break;
       }
       ptr = ptr.getLink();
      }
      size--;
     }

     public void display() {
      System.out.print("Elements in the list : ");
      if (size == 0) {
       System.out.print("empty\n");
       return;
      }
      if (start.getLink() == null) {
       System.out.println(start.getData());
       return;
      }
      Node ptr = start;
      System.out.print(start.getData() + "\t");
      ptr = start.getLink();
      while (ptr.getLink() != null) {
       System.out.print(ptr.getData() + "\t");
       ptr = ptr.getLink();
      }
      System.out.print(ptr.getData() + "\n");
     }
    }

    public class LinkedList {
     public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      int ch;
      char ans = 'Y';
      LL ll = new LL();
      while (ans == 'Y' || ans == 'y') {
       System.out.println("\n1.Insert node at first");
       System.out.println("2.Insert node at last");
       System.out.println("3.Insert node at position");
       System.out.println("4.Delete Node from any Position");
       System.out.println("5.Display");
       System.out.println("6.Exit\n");
       System.out.print("Enter your choice: \t");
       ch = scan.nextInt();
       switch (ch) {
       case 1:
        System.out.print("Enter value for the node : \t");
        ll.insertAtStart(scan.nextInt());
        break;
       case 2:
        System.out.print("Enter value for the node : \t");
        ll.insertAtEnd(scan.nextInt());
        break;
       case 3:
        System.out.print("Enter value for the node : \t");
        int num = scan.nextInt();
        System.out.print("Enter position : \t");
        int pos = scan.nextInt();
        if (pos <= 1 || pos > ll.size)
         System.out.println("Invalid position\n");
        else
         ll.insertAtPos(num, pos);
        break;
       case 4:
        System.out.print("Enter position: \t");
        int dpos = scan.nextInt();
        if (dpos < 1 || dpos > ll.size)
         System.out.println("Invalid position\n");
        else
         ll.deleteAtPos(dpos);
        break;
       case 5:
        ll.display();
        break;
       case 6:
        return;
       default:
        System.out.println("\nInvalid Choice\n");
        break;
       }
       System.out.print("Do you want to continue ? (Y/N) \t");
       ans = scan.next().charAt(0);
      }
      scan.close();
     }
    }
Download code

OUTPUT :



Java - Linked List Operations - Insertion at front
Java - Linked List Operations - Insertion at last

Java - Linked List Operations - Insertion at position
Java - Linked List Operations - Deletion
Download code

Tuesday, 23 February 2016

Data Structures - Cpp Program to implement Linked List Operations - Insert , Delete , Update , Display

Linked List is another data structure consisting of group of nodes which together represent a sequence. Each node has two parts one for the value and other for link to the next node.
Linked lists allows dynamic memory allocation.

Singly-linked-list.svg
A singly linked list whose nodes contain two fields: an integer value and a link to the next node


Some of the operations in a linked list are :

  • Insertion into the list
  • Deletion from the list
  • Updation of the value
  • Display the list





Download code

PROGRAM :

        #include<iostream>
 #include<cstdio>
 #include<cstdlib>

 using namespace std;


 struct node
 {
     int value;
     struct node *next;
 }*start;

 typedef struct node snode;
 snode *newnode, *ptr, *prev, *temp;
 snode *first = NULL, *last = NULL;

 class LinkedList
 {
 public:
     node* create_node(int);
     void insertNodeFirst();
     void insertNodeLast();
     void insertNodePosition();
     void deleteNode();
     void updateNode();
     void displayList();
     LinkedList()
     {
  start = NULL;
     }
 };

 int main()
 {
     int ch;
     char ans = 'Y';
     LinkedList ll;
     while (ans == 'Y'||ans == 'y')
     {
  cout << "\n1.Insert node at first";
  cout << "\n2.Insert node at last";
  cout << "\n3.Insert node at position";
  cout << "\n4.Delete Node from any Position";
  cout << "\n5.Update Node Value";
  cout << "\n6.Display List";
  cout << "\n7.Exit\n";
  cout << "\nEnter your choice: \t";
  cin >> ch;

  switch (ch)
  {
  case 1:
      ll.insertNodeFirst();
      break;
  case 2:
      ll.insertNodeLast();
      break;
  case 3:
      ll.insertNodePosition();
      break;
  case 4:
      ll.deleteNode();
      break;
  case 5:
      ll.updateNode();
      break;
  case 6:
      ll.displayList();
      break;
  case 7:
      return 0;
      break;
  default:
      cout << "\nInvalid Choice\n";
      break;
  }
  cout << "\nDo you want to continue ? (Y/N) \t";
  cin >> ans;
     }
     return 0;
 }
 snode* createNode(int val)
 {
     newnode = (snode *)malloc(sizeof(snode));
     if (newnode == NULL)
     {
  cout << "\nMemory was not allocated";
  return 0;
     }
     else
     {
  newnode->value = val;
  newnode->next = NULL;
  return newnode;
     }
 }
 void LinkedList::insertNodeFirst()
 {
     int val;
     cout << "\nEnter the value for the node: \t";
     cin >> val;
     newnode = createNode(val);
     if (first == last && first == NULL)
     {
  first = last = newnode;
  first->next = NULL;
  last->next = NULL;
     }
     else
     {
  temp = first;
  first = newnode;
  first->next = temp;
     }
     cout << "\nInserted Successfully";
 }
 void LinkedList::insertNodeLast()
 {
     int val;

     cout << "\nEnter the value for the Node: \t";
     cin >> val;
     newnode = createNode(val);
     if (first == last && last == NULL)
     {
  first = last = newnode;
  first->next = NULL;
  last->next = NULL;
     }
     else
     {
  last->next = newnode;
  last = newnode;
  last->next = NULL;
     }
     cout << "\nInserted Successfully";
 }
 void LinkedList::insertNodePosition()
 {
     int pos, val, count = 0, i;
     cout << "\nEnter the value for the Node: \t";
     cin >> val;
     newnode = createNode(val);
     cout << "\nEnter the position: \t";
     cin >> pos;
     ptr = first;
     while (ptr != NULL)
     {
  ptr = ptr->next;
  count++;
     }
     if (pos == 1)
     {
  if (first == last && first == NULL)
  {
      first = last = newnode;
      first->next = NULL;
      last->next = NULL;
  }
  else
  {
      temp = first;
      first = newnode;
      first->next = temp;
  }
  cout << "\nInserted Successfully";
     }
     else if (pos>1 && pos<=count)
     {
  ptr = first;
  for (i = 1; i < pos; i++)
  {
      prev = ptr;
      ptr = ptr->next;
  }
  prev->next = newnode;
  newnode->next = ptr;
  cout << "\nInserted Successfully";
     }
     else
     {
  cout << "Position is out of range";
     }
 }
 void LinkedList::deleteNode()
 {
     int pos, count = 0, i;

     if (first == NULL)
     {
  cout << "No nodes in the list to delete\n";
     }
     else
     {
  cout << "\nEnter the position of value to be deleted: \t";
  cin >> pos;
  ptr = first;
  if (pos == 1)
  {
      first = ptr->next;
      cout << "\nElement deleted successfully";
  }
  else
  {
      while (ptr != NULL)
      {
          ptr = ptr->next;
          count = count + 1;
      }
      if (pos > 0 && pos <= count)
      {
          ptr = first;
          for (i = 1; i < pos; i++)
          {
              prev = ptr;
              ptr = ptr->next;
          }
          prev->next = ptr->next;
      }
      else
      {
          cout << "Position is out of range";
      }
      free(ptr);
      cout << "\nElement deleted successfully";
  }
     }
 }
 void LinkedList::updateNode()
 {
     int oldval, newval, flag = 0;

     if (first == NULL)
     {
  cout << "No nodes in the list to update\n";
     }
     else
     {
  cout << "\nEnter the value to be updated: \t";
  cin >> oldval;
  cout << "\nEnter the new value: \t";
  cin >> newval;
  for (ptr = first; ptr != NULL; ptr = ptr->next)
  {
      if (ptr->value == oldval)
      {
          ptr->value = newval;
          flag = 1;
          break;
      }
  }
  if (flag == 1)
  {
      cout << "\nUpdated Successfully";
  }
  else
  {
      cout << "\nValue not found in List";
  }
     }
 }
 void LinkedList::displayList()
 {
     if (first == NULL)
     {
  cout << "No nodes in the list to display\n";
     }
     else
     {
  for (ptr = first; ptr != NULL; ptr = ptr->next)
  {
      cout <<  ptr->value << "\t";
  }
     }
 }
 
Download code

OUTPUT :

Cpp - Linked List Operations - Insertion at front

Cpp - Linked List Operations - Insertion at last and  any position

Cpp - Linked List Operations -  Deletion of node

Cpp - Linked List Operations - Updation of value

Cpp - Linked List Operations - Display List
Download code

Monday, 22 February 2016

Data Structures - C Program to implement Linked List Operations - Insert , Delete , Update , Display

Linked List is another data structure consisting of group of nodes which together represent a sequence. Each node has two parts one for the value and other for link to the next node.
Linked lists allows dynamic memory allocation.

Singly-linked-list.svg
A singly linked list whose nodes contain two fields: an integer value and a link to the next node



Some of the operations in a linked list are :

  • Insertion into the list
  • Deletion from the list
  • Updation of the value
  • Display the list





Download code

PROGRAM :

#include <stdio.h>
 #include <stdlib.h>
 #include <malloc.h>

 struct node
 {
     int value;
     struct node *next;
 };
 typedef struct node snode;
 snode *newnode, *ptr, *prev, *temp;
 snode *first = NULL, *last = NULL;

 int main()
 {
     int ch;
     char ans = 'Y';
     while (ans == 'Y'||ans == 'y')
     {
  printf("\n1.Insert node at first");
  printf("\n2.Insert node at last");
  printf("\n3.Insert node at position");
  printf("\n4.Delete Node from any Position");
  printf("\n5.Update Node Value");
  printf("\n6.Display List");
  printf("\n7.Exit\n");
  printf("\nEnter your choice: \t");
  scanf("%d", &ch);

  switch (ch)
  {
  case 1:
      insertNodeFirst();
      break;
  case 2:
      insertNodeLast();
      break;
  case 3:
      insertNodePosition();
      break;
  case 4:
      deleteNode();
      break;
  case 5:
      updateNode();
      break;
  case 6:
      displayList();
      break;
  case 7:
      return 0;
      break;
  default:
      printf("\n...Invalid Choice...\n");
      break;
  }
  printf("\nDo you want to continue ? (Y/N) \t");
  scanf(" %c", &ans);
     }
     return 0;
 }
 snode* createNode(int val)
 {
     newnode = (snode *)malloc(sizeof(snode));
     if (newnode == NULL)
     {
  printf("\nMemory was not allocated");
  return 0;
     }
     else
     {
  newnode->value = val;
  newnode->next = NULL;
  return newnode;
     }
 }
 void insertNodeFirst()
 {
     int val;
     printf("\nEnter the value for the node: \t");
     scanf("%d", &val);
     newnode = createNode(val);
     if (first == last && first == NULL)
     {
  first = last = newnode;
  first->next = NULL;
  last->next = NULL;
     }
     else
     {
  temp = first;
  first = newnode;
  first->next = temp;
     }
     printf("\nInserted Successfully");
 }
 void insertNodeLast()
 {
     int val;

     printf("\nEnter the value for the Node: \t");
     scanf("%d", &val);
     newnode = createNode(val);
     if (first == last && last == NULL)
     {
  first = last = newnode;
  first->next = NULL;
  last->next = NULL;
     }
     else
     {
  last->next = newnode;
  last = newnode;
  last->next = NULL;
     }
     printf("\nInserted Successfully");
 }
 void insertNodePosition()
 {
     int pos, val, count = 0, i;
     printf("\nEnter the value for the Node: \t");
     scanf("%d", &val);
     newnode = createNode(val);
     printf("\nEnter the position: \t");
     scanf("%d", &pos);
     ptr = first;
     while (ptr != NULL)
     {
  ptr = ptr->next;
  count++;
     }
     if (pos == 1)
     {
  if (first == last && first == NULL)
  {
      first = last = newnode;
      first->next = NULL;
      last->next = NULL;
  }
  else
  {
      temp = first;
      first = newnode;
      first->next = temp;
  }
  printf("\nInserted Successfully");
     }
     else if (pos>1 && pos<=count)
     {
  ptr = first;
  for (i = 1; i < pos; i++)
  {
      prev = ptr;
      ptr = ptr->next;
  }
  prev->next = newnode;
  newnode->next = ptr;
  printf("\nInserted Successfully");
     }
     else
     {
  printf("Position is out of range");
     }
 }
 void deleteNode()
 {
     int pos, count = 0, i;

     if (first == NULL)
     {
  printf("No nodes in the list to delete\n");
     }
     else
     {
  printf("\nEnter the position of value to be deleted: \t");
  scanf(" %d", &pos);
  ptr = first;
  if (pos == 1)
  {
      first = ptr->next;
      printf("\nElement deleted successfully");
  }
  else
  {
      while (ptr != NULL)
      {
          ptr = ptr->next;
          count = count + 1;
      }
      if (pos > 0 && pos <= count)
      {
          ptr = first;
          for (i = 1; i < pos; i++)
          {
              prev = ptr;
              ptr = ptr->next;
          }
          prev->next = ptr->next;
      }
      else
      {
          printf("Position is out of range");
      }
      free(ptr);
      printf("\nElement deleted successfully");
  }
     }
 }
 void updateNode()
 {
     int oldval, newval, flag = 0;

     if (first == NULL)
     {
  printf("No nodes in the list to update\n");
     }
     else
     {
  printf("\nEnter the value to be updated: \t");
  scanf("%d", &oldval);
  printf("\nEnter the new value: \t");
  scanf("%d", &newval);
  for (ptr = first; ptr != NULL; ptr = ptr->next)
  {
      if (ptr->value == oldval)
      {
          ptr->value = newval;
          flag = 1;
          break;
      }
  }
  if (flag == 1)
  {
      printf("\nUpdated Successfully");
  }
  else
  {
      printf("\nValue not found in List");
  }
     }
 }
 void displayList()
 {
     if (first == NULL)
     {
  printf("No nodes in the list to display\n");
     }
     else
     {
  for (ptr = first; ptr != NULL; ptr = ptr->next)
  {
      printf("%d\t", ptr->value);
  }
     }
 }
 

Download code

OUTPUT :

C - Linked List Operations - Insertion at front

C - Linked List Operations - Insertion at last and  any position

C - Linked List Operations -  Deletion of node

C - Linked List Operations - Updation of value

C - Linked List Operations - Display List

Tuesday, 16 February 2016

Data Structures - Cpp Program to implement queue operations using an array

Queue is a data structure  , similar to Stack , but here in queue we have openings at both the ends , one for insertion and other for deletion.


Some of the common operations of queue are :

  • Adding an item to queue(enqueue)
  • Removing an item from a queue(dequeue)
  • Overflow Condition(Queue full)
  • Underflow Condition(Queue empty)
  • Getting the front element(peek)



Overflow situation occur when the queue is full and then we are trying to  insert/add another item to the queue .

Underflow situation occur when the queue is empty and the we are trying to remove/delete an item from the queue.

The principle of  queue is First In First Out (FIFO).


Download code

PROGRAM :

#include <iostream>

using namespace std;

int main()
{
    int rear = -1,front = -1,item,MAX ,choice ,i;
    cout << "Enter Size of Queue : \t ";
    cin >> MAX;
    int QueueArray[MAX];
    while (1)
    {
        cout << "\nQueue Operations  :";
        cout << "\n1. Insert/Add";
        cout << "\n2. Remove/Delete";
        cout << "\n3. Peek/Front item";
        cout << "\n4. Display Queue";
        cout << "\n5. Exit";
        cout << "\nEnter your choice :\t";
        cin >> choice;
        switch (choice)
        {
        case 1:
            if (rear == MAX - 1)
            {
                cout << "Queue Overflow \n";
            }
            else
            {
                if (front == -1)
                {
                    front = 0;
                }
                cout << "Inset the element in queue : \t";
                cin >> item;
                rear = rear + 1;
                QueueArray[rear] = item;
            }

            break;
        case 2:

            if (front == -1 || front > rear)
            {
                cout << "Queue Underflow \n";
                break;
            }
            else
            {
                cout << "Element deleted from queue is " <<  QueueArray[front] << "\n" ;
                front = front + 1;
            }
            break;
        case 3:
            if (front == -1 || front > rear)
            {
                cout << "Queue Underflow \n";
                break;
            }
            else
            {
                cout << "The front element is :" << QueueArray[front] << "\t" ;
            }
            break;
        case 4:
            if (front == -1 || front > rear)
            {
                cout << "Queue Underflow \n";
                break;
            }
            else
            {
                cout << "The current elements in queue are :";
                for (i = front; i <= rear; i++)
                {
                    cout << QueueArray[i];
                }
            }
            break;
        case 5:
            return 0;
            break;
        default:
            cout << "Wrong Entry \n ";
            break;
        }

    }
    return 0;
}
Download code

OUTPUT : 

Cpp - Queue Operations
Cpp- Queue Overflow
   
Cpp - Queue Underflow
Download code

Data Structures - C Program to implement queue operations using an array

Queue is a data structure  , similar to Stack , but here in queue we have openings at both the ends , one for insertion and other for deletion.


Some of the common operations of queue are :

  • Adding an item to queue(enqueue)
  • Removing an item from a queue(dequeue)
  • Overflow Condition(Queue full)
  • Underflow Condition(Queue empty)
  • Getting the front element(peek)



Overflow situation occur when the queue is full and then we are trying to  insert/add another item to the queue .

Underflow situation occur when the queue is empty and the we are trying to remove/delete an item from the queue.

The principle of  queue is First In First Out (FIFO).

Download code


PROGRAM :

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

int main()
{
    int rear = -1,front = -1,item,MAX ,choice ,i;
    printf("Enter Size of Queue : \t ");
    scanf("%d" , &MAX);
    int QueueArray[MAX];
    while (1)
    {
        printf("\nQueue Operations  :");
        printf("\n1. Insert/Add");
        printf("\n2. Remove/Delete");
        printf("\n3. Peek/Front item");
        printf("\n4. Display Queue");
        printf("\n5. Exit");
        printf("\nEnter your choice :\t");
        scanf("%d" , &choice);
        switch (choice)
        {
        case 1:
            if (rear == MAX - 1)
            {
                printf("Queue Overflow \n");
            }
            else
            {
                if (front == -1)
                {
                    front = 0;
                }
                printf("Inset the element in queue : \t");
                scanf("%d" , &item);
                rear = rear + 1;
                QueueArray[rear] = item;
            }

            break;
        case 2:

            if (front == -1 || front > rear)
            {
                printf("Queue Underflow \n");
                break;
            }
            else
            {
                printf("Element deleted from queue is %d \n" , QueueArray[front] );
                front = front + 1;
            }
            break;
        case 3:
            if (front == -1 || front > rear)
            {
                printf("Queue Underflow \n");
                break;
            }
            else
            {
                printf("The front element is : %d \t" , QueueArray[front]);
            }
            break;
        case 4:
            if (front == -1 || front > rear)
            {
                printf("Queue Underflow \n");
                break;
            }
            else
            {
                printf("The current elements in queuue are :");
                for (i = front; i <= rear; i++)
                {
                    printf("%d " ,QueueArray[i]);
                }
            }
            break;
        case 5:
            return 0;
            break;
        default:
            printf("Wrong Entry \n ");
            break;
        }

    }
    return 0;
}
Download code

OUTPUT :

C - Queue Operations
C- Queue Overflow
   
C - Queue Underflow


Download code

Monday, 15 February 2016

Data Structures - Java Program to implement queue operations using an array


Queue is a data structure  , similar to Stack , but here in queue we have openings at both the ends , one for insertion and other for deletion.


Some of the common operations of queue are :

  • Adding an item to queue(enqueue)
  • Removing an item from a queue(dequeue)
  • Overflow Condition(Queue full)
  • Underflow Condition(Queue empty)
  • Getting the front element(peek)



Overflow situation occur when the queue is full and then we are trying to  insert/add another item to the queue .

Underflow situation occur when the queue is empty and the we are trying to remove/delete an item from the queue.

The principle of queue is First In First Out (FIFO).



Download code

PROGRAM :

package mycodingcorner;

import java.util.Scanner;

public class Queue_Array {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int rear = -1;
        int front = -1;
        int item;
        System.out.print("Enter Size of Queue : \t ");
        int MAX = scan.nextInt();
        int QueueArray[] = new int[MAX];
        while (true) {
            System.out.println("\nQueue Operations  :");
            System.out.println("1.Insert/Add");
            System.out.println("2. Remove/Delete");
            System.out.println("3. Peek/Front item");
            System.out.println("4. Display Queue");
            System.out.println("5. Exit");
            System.out.print("Enter your choice :\t");
            int choice = scan.nextInt();
            switch (choice) {
                case 1:
                    if (rear == MAX - 1) {
                        System.out.println("Queue Overflow \n");
                    } else {
                        if (front == -1) {
                            front = 0;
                        }
                        System.out.print("Inset the element in queue : \t");
                        item = scan.nextInt();
                        rear = rear + 1;
                        QueueArray[rear] = item;
                    }

                    break;
                case 2:

                    if (front == -1 || front > rear) {
                        System.out.println("Queue Underflow \n");
                        return;
                    } else {
                        System.out.println("Element deleted from queue is " + QueueArray[front] + "\n");
                        front = front + 1;
                    }
                    break;
                case 3:
                    if (front == -1 || front > rear) {
                        System.out.println("Queue Underflow \n");
                        return;
                    } else {
                        System.out.println("The front element is : \t" + QueueArray[front]);
                    }
                    break;
                case 4:
                    if (front == -1 || front > rear) {
                        System.out.println("Queue Underflow \n");
                        return;
                    } else {
                        System.out.print("The current elements in queuue are :");
                        for (int i = front; i <= rear; i++) {
                            System.out.print(QueueArray[i] + " ");
                        }
                    }
                    break;
                case 5:
                    System.exit(0);
                    break;
                default:
                    System.out.println("Wrong Entry \n ");
                    break;
            }

        }
    }
}
Download code

OUTPUT :

Java - Queue Operations


Java - Queue Underflow

Java - Queue Overflow

Friday, 16 January 2015

Data Structures - Cpp Program to implement stack operations



In this post we will see some basic operations of stack like insertion , deletion . Generally a stack is a an abstract data type where insertion and deletion takes place at one end and that end is know as top.

Inserting an item to stack is called as PUSH operation.
Removing an item from a stack is called as POP operation.

Inserting or deleting an item takes place at one end and they are done one by one.



See the image below
Data stack.svg
"Data stack" by User:Boivie - made in Inkscape, by myself User:Boivie. Based on Image:Stack-sv.png, originally uploaded to the Swedish Wikipedia in 2004 by sv:User:Shrimp. Licensed under Public Domain via Wikimedia Commons.



The principle of the stack is : Last In First Out (LIFO)
Here in this program we initially take top as -1 and when an element is inserted top is incremented and pushes the value in stack , similarly when when an element is deleted top is decremented and pops the value from stack.

There are two error conditions here :
  1. Stack Overflow
  2. Stack Underflow
Stack Overflow is a situation where the stack is full and we still trying to insert elements to that stack.
Stack Underflow is a situation where the stack is empty and we are still trying to delete  elements from that stack.

PROGRAM : 
#include <iostream>
#define MAX 10
using namespace std;
void push(int);
int pop();
int top = -1;
int stack[MAX];
int main()
{
    int element,choice,d;

    while(1)
    {
        cout << "\nSTACK OPERATIONS \n\n";
        cout << "1.Insert \n";
        cout << "2.Delete \n";
        cout << "3.Display \n";
        cout << "4.Exit\n\n";
        cout << "Enter your choice. \t";
        cin >> choice;

        switch (choice)
        {
        case 1:
            if ( top == MAX - 1 )
                cout << "\nSTACK is already full. Delete some elements and try again ! \n ERROR : STACK OVERFLOW\n";
            else
            {
                cout << "\nEnter the value to insert.\t";
                cin >> element;
                push(element);
            }
            break;
        case 2:
            if ( top == -1 )
                cout << "\nSTACK is already empty. \n ERROR : STACK UNDERFLOW\n";
            else
            {
                element = pop();
                cout << "Element removed from stack is "<<  element<< endl;
            }
            break;
        case 3:
            if ( top == -1 )
                cout << "\nSTACK is empty. Cannot display anything\n";
            else
            {
                cout << "There are"<< (top+1)<<"elements in stack.\n";

                for ( d = top ; d >= 0 ; d-- )
                    cout <<  stack[d] << endl;

            }
            break;
        case 4:
            return 0;
        }
    }
    return 0;
}
void push(int value)
{
    top++;
    stack[top] = value;
}
int pop()
{
    int element;
    if ( top == -1 )
        return top;

    element = stack[top];
    top--;

    return element;
}

OUTPUT : 
Cpp - Stack Operations

Cpp - Stack Operations


Cpp - Stack Operations


Cpp - Stack Operations