FoodForFutureGeeks

Tuesday, 8 January 2013

Doubly Linked List Implementation

Following program gives Implementation of Doubly Linked List with its various operations:


/*************************************************************
* Author: Aniruddha S N
* 
*/

#include<iostream>
using namespace std;

// structure node
struct node
{
    int info;
    struct node* next;
    struct node* prev;
};

//function declarations
 void display_list();
 void Insert_Element_List(int ele);
 void DeleteElementAtPos(int pos);
 void display_Prev_Next(int pos);
 void delete_Entire_list();

 //global variable first
 node* first = NULL;

 //main function
int main()
{    
    int ele = 0;
    int ch  = 0;
    int pos = 0;

//Menu to display Doubly linked list operations
    while(1)
    {
        cout<<"**************DoublyLinkedListOperationsMenu*************\n";
        cout<<"1---->Insert an element in list\n";
        cout<<"2---->displayList\n";
        cout<<"3---->DeleteAnElement at specified position in list\n";
        cout<<"4---->Display Previous and Next ele of the mentioned node\n";
        cout<<"5---->exit\n";
        cout<<"***************************************************\n";
        cout<<"\n\n";
        cout<<"Enter your choice:\n";
        cin>>ch;

        //using switch case call respective functions for respective choices
        switch(ch)
        {
        case 1: cout<<"Enter the element to be inserted into list\n";
                cin>>ele;
                Insert_Element_List(ele);
                break;
        case 2:display_list();
               break;
        case 3:cout<<"Enter the position to delete elements\n";
               cin>>pos;
               DeleteElementAtPos(pos);
               break;
        case 4:cout<<"Enter the Node Position to display previous and next ele\n";
               cin>>pos;
               display_Prev_Next(pos);
               break;
        default: delete_Entire_list();
                 exit(0);
        }

    }
     return 0;
}//end of main

//function to insert an element in singly linked list
void  Insert_Element_List(int ele)
{
    node* temp;
     if(first == NULL)
     {
         first= new node();
         first->info=ele;
         first->next=NULL;
         first->prev=NULL;
     }
     else
     {
         node* temp1;
         temp1 = new node();
         temp=first;

     //find the end of list
         while( temp->next != NULL)
             temp=temp->next;

         temp1->info=ele;
         temp1->next=NULL;
     //attach the new node at the end of list
         temp->next=temp1;
         temp1->prev=temp;
     }
}


//function to display the elements in the list
void  display_list()
{
    if ( first == NULL)
        cout<<"list doesnt have any elements";

    else if(first->next == NULL)
    {
        cout<<"List Contents:\n";
        cout<<first->info<<"\n";
    }

    else
    {
        node* temp;
        temp=first;
        cout<<"List Contents:\n";
        while( temp != NULL)
        {
            cout<<temp->info<<"\n";
            temp=temp->next;
        }
    }
}

//function to delete element at specified position
void DeleteElementAtPos(int pos)
{
    int flag = 0;
    node* prev;
    node* temp;


    if( first == NULL )
    { cout<<"List Empty\n";
    }

    else if( pos >1 && first->next == NULL )
    {
        cout<<"No element at specified position in list\n";
    }
            
    else if( pos ==1)
      {
            temp=first;
            prev=temp;
            temp=temp->next;
             temp->prev=NULL;
            //re initiate first
            first=temp;
            prev->next=NULL;
            prev->prev=NULL;
            delete prev;
            prev= NULL;
            
        }

    // for all other positions
    else
    {

        temp=first;
        flag=1;
        while(flag < pos && temp->next != NULL)
        {
           prev=temp;
           temp=temp->next;
           flag++;
        }
        //check whether the specified position exists
        if( flag < pos)
        {
            cout<<"No element at specified position in list\n";
        }
        //delete the node at the specified position
        else
        {
            prev->next = temp->next;
            temp->next->prev=prev;

            temp->next=NULL;
            temp->prev=NULL;
            delete temp;
            temp=NULL;
        }
    
    }//end of else for all other positions
}

void display_Prev_Next(int pos)
{
    if(first == NULL)
        cout<<"List empty\n";
    else if(first->next == NULL)
        cout<<"Only one element in List\n";
    //for other valid cases
    else
    {
        node* temp=first;
        node* prev;
        int flag=1;
        while( flag < pos && temp->next!=NULL)
        {
            prev=temp;
            flag++;
            temp=temp->next;
        }
        //check whether its an invalid node position
        if(flag < pos)
        {
            cout<<"No element at specified position in the list\n";
        }
        //if the position is valid
        else
        {
            cout<<"Previous Node:"<<prev->info<<"\n";
            cout<<"Current  Node:"<<temp->info<<"\n";
            if(temp->next == NULL)
                cout<<"Next Node:End of List\n";
            else
            cout<<"Next Node:"<<temp->next->info<<"\n";
        }
    }
    //end of else other valid cases
}

//function to delete entire list and prevent memory leakage when exit is called
void delete_Entire_list()
{
    node* temp;
    node* curr;
    temp=first;
    if(first == NULL)
        return;
    while(temp->next != NULL)
    {
      curr=temp;
      temp=temp->next;
      delete curr;
    }
    delete temp;
}

Monday, 7 January 2013

LinkedListImplementationUsing Structures

Singly Linked List with its operations :
/*************************************************************
* Author: Aniruddha S N
* 
*/

#include<iostream>
using namespace std;

// structure node
struct node
{
    int info;
    struct node* next;
};

//function declarations
 void display_list();
 void Insert_Element_List(int ele);
 void DeleteElementAtPos(int pos);

 //global variable first
 node* first = NULL;

 //main function
int main()
{    
    int ele = 0;
    int ch  = 0;
    int pos = 0;

//Menu to display single linked list operations
    while(1)
    {
        cout<<"**************LinkedListOperationsMenu*************\n";
        cout<<"1---->Insert an element in list\n";
        cout<<"2---->displayList\n";
        cout<<"3---->DeleteAnElement at specified position in list\n";
        cout<<"4---->exit\n";
        cout<<"***************************************************\n";
        cout<<"\n\n";
        cout<<"Enter your choice:\n";
        cin>>ch;

        //using switch case call respective functions for respective choices
        switch(ch)
        {
        case 1: cout<<"Enter the element to be inserted into list\n";
                cin>>ele;
                Insert_Element_List(ele);
                break;
        case 2:display_list();
               break;
        case 3:cout<<"Enter the position to delete elements\n";
               cin>>pos;
               DeleteElementAtPos(pos);
               break;
        default: exit(0);
        }

    }
     return 0;
}//end of main

//function to insert an element in singly linked list
void  Insert_Element_List(int ele)
{
    node* temp;
     if(first == NULL)
     {
         first= new node();
         first->info=ele;
         first->next=NULL;
     }
     else
     {
         node* temp1;
         temp1 = new node();
         temp=first;

     //find the end of list
         while( temp->next != NULL)
             temp=temp->next;

         temp1->info=ele;
         temp1->next=NULL;
     //attach the new node at the end of list
         temp->next=temp1;
     }
}


//function to display the elements in the list
void  display_list()
{
    if ( first == NULL)
        cout<<"list doesnt have any elements";

    else if(first->next == NULL)
    {
        cout<<"List Contents:\n";
        cout<<first->info<<"\n";
    }

    else
    {
        node* temp;
        temp=first;
        cout<<"List Contents:\n";
        while( temp != NULL)
        {
            cout<<temp->info<<"\n";
            temp=temp->next;
        }
    }
}

//function to delete element at specified position
void DeleteElementAtPos(int pos)
{
    int flag = 0;
    node* prev;
    node* temp;


    if( first == NULL )
    { cout<<"List Empty\n";
    }

    else if( pos >1 && first->next == NULL )
    {
        cout<<"No element at specified position in list\n";
    }
            
    else if( pos ==1)
      {
            temp=first;
            prev=temp;
            temp=temp->next;

            //re initiate first
            first=temp;
            delete prev;
            prev= NULL;
            
        }

    // for all other positions
    else
    {

        temp=first;
        flag=1;
        while(flag < pos && temp->next != NULL)
        {
           prev=temp;
           temp=temp->next;
           flag++;
        }
        //check whether the specified position exists
        if( flag < pos)
        {
            cout<<"No element at specified position in list\n";
        }
        //delete the node at the specified position
        else
        {
            prev->next = temp->next;
            delete temp;
            temp=NULL;
        }
    
    }//end of else for all other positions
}

Thursday, 3 January 2013

Stack Implementation using arrays with Menu for various operations.


This Program gives stack implementation using arrays, max stack size input 
is considered as 100 during implementation, modify it suitably.

#include<stdio.h>
#include<conio.h>

//Max stack size can be 99
//function declaration
void push(int* top,int* stackarray,int size, int ele);
void pop(int *top,int* stackarray);
void display_stack(int stackarray[],int top);


//main function
void main()
{
  int stackarr[100];
  int top          =-1;
  int size         =0;
  int ele          =0;
  int ch           =0;




  printf("enter the stack size less than 100\n");
  scanf("%d",&amp;size);


  //this menu will be displayed till user chooses to exit
    while(1)
   {
      printf("***************stackOperationsMenu*****************\n");
      printf("1--------->push an element int stack\n");
      printf("2--------->pop an element into stack\n");
      printf("3--------->display stack contents\n");
      printf("otherNum------>exit the program\n");
      printf("Enter your choice\n");
      scanf("%d", &ch);
      switch(ch)
      {
      case 1:printf("Enter the element to be pushed to stack\n");
             scanf("%d", &ele);
             push( &top,stackarr,size,ele);
             break;
      case 2:pop( &top,stackarr);
             break;
      case 3: display_stack(stackarr,top);
              break;


      default:return;
      }//end of switch
   }//end of while


  }// end of main


//function definitions
void push(int* top,int* stackarray,int size, int ele)
{
    if(*top  == size-1)
    {

        printf("stack is full\nPlease pop some elements and try to insert again\n");
    }
    else
    {  *top=*top+1;
        stackarray[*top]=ele;
    }
}
void pop(int* top,int* stackarray)
{
    if(*top == -1)
        printf(" stack is empty no element to pop\n");
    else
    {
        printf("Popped element is %d",stackarray[*top--]);
    }
}
void display_stack(int stackarray[],int top)
{
    int i=0;
    printf("Stack contents:\n");
    for(int i=0;i&amp;lt;=top;i++)
    {
        printf("%d\n",stackarray[i]);
    } 
} 

Friday, 29 June 2012

Program to Read a file line by line in C++


#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string strfile="filenamewithabsolutepath.txt";
 ifstream ifptr;
 ifptr.open(strfile);
if(!ifptr.is_open())
{
 cout<<"Unable to open file\n";
 }
 else{
 //read the file till the end
    while(!ifptr.eof())
    {
     string line;
     getline(ifptr,line);
     cout<<"line:"<<line<<"\n";
    }//end of while
   }//end of else
   return 0;
 }//end of main

Friday, 22 June 2012

Program to Reverse a String

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;
int main()
{
char* original_string="abcdefg";
char* reverse_string;
char* temp;
int length_original=0;
int length_reverse=0;
temp=original_string;
 
//find the length of string
while(*temp!=NULL)
{
 temp++;
length_original++;
}
//assign memory to reverse_string
reverse_string=new char[length_original];
while(length_original>0)
{
 reverse_string[length_reverse++]=*--temp;
 length_original--;
}
//store null as last character
reverse_string[length_reverse]='\0';
cout<<"Original string:"<<original_string;
cout<<"\nReverse string:"<<reverse_string;
return 0;
}

Output:

Original string:abcdefg
Reverse string:gfedcba


Saturday, 21 April 2012

Arrays, 2D arrays, 3D arrays.

Array:

An array is a collection of homogeneous variables, all the variables in the array should be of same datatype.
declaration of an array:an array is declared like a normal variable but it is followed by a pair of square braces.
#include<stdio.h>
void main()
{

//the array size is specified in square braces
int a[10];
//we can assign values during declaration itself using flower braces.
float f[5]={0,1,2,3,4};
}
Sample program:
//This program demonstrates 
//1.How to store values in an array
//2.How to access values stored in array
#include<stdio.h>
void main()
{

//Array declaration
int array[10];
int i=0;
//storing values in the array
printf("enter the values of 10 nos:\n");
for( i=0;i<10;i++ )
{
 scanf("%d",&array[i]);
}
//accessing the values stored in array
for( i=0;i<10;i++ )
{
printf("array location:%d has value:%d\n",i,array[i]);
}
}

Two dimensional arrays:

A two dimensional array can be considered as a matrix like storage structure, elements are stored in rows and columns.

general format:
variablename[m][n];
m is the number of rows
n is the number of columns.

ex:
int a[2][4]={1,2,3,4,5,6,7,8};

logical storage 
[ 1  2  3  4
  5  6  7  8]
Note:
The matrix like storage structure is only logical assumption, but the actual storage of variables in memory need not be so.

Sample program:
//This program demonstrates 
//1.How to store values in a 2Darray
//2.How to access values stored in a 2D array
#include<stdio.h>
void main()
{
 
//Array declaration
int array[2][2];
int i=0;
int j=0;
//storing values in the array
printf("enter the values of 4 nos:\n");
for( i=0;i<2;i++ )//row traversal
{
 for( j=0;j<2;j++)//column traversal
  {
   scanf("%d",&array[i][j]);
  }
}
//accessing the values stored in array
for( i=0;i<2;i++ )//row traversal
{
 for(j=0;j<2;j++)//column traversal
   {
    printf("array location:%d has value:%d\n",i,array[i][j]);
   }
}
}
enter the values of 4 nos:
1 2 3 4
array location:0 has value:1 array location:0 has value:2 array location:1 has value:3 array location:1 has value:4

Three Dimensional Arrays:

Three dimensional arrays are like multiple copies of the same matrix.
Standard format:
variablename[no of matrix][no of rows][no of columns]
ex: int a[2][3][3]; two matrices with 3 rows and 3 columns.

sample program:
//This program demonstrates 
//1.How to store values in a 3Darray
//2.How to access values stored in a 3D array
#include<stdio.h>
void main()
{
 
//Array declaration
int array[2][2][2];
int i=0;
int j=0;
int k=0;
//storing values in the array
printf("enter the values of 8 nos:\n");
for(k=0;k<2;k++)//traverse the matrix copy
{
for( i=0;i<2;i++ )//row traversal
{
 for( j=0;j<2;j++)//column traversal
  {
   scanf("%d",&array[k][i][j]);
  }
}
}
//accessing the values stored in array
for( k=0;k<2;k++)//traverse the matrix copy
{
printf("Matrix no:%d\n",k);
for( i=0;i<2;i++ )//row traversal
{
 for(j=0;j<2;j++)//column traversal
   {
    printf("array location:%d has value:%d\n",i,array[k][i][j]);
   }//end of j loop
 }//end of i loop
}//end of k loop
}

enter the values of 8 nos:
1 2 3 4 5 6 7 8
Matrix no:0 array location:0 has value:1 array location:0 has value:2 array location:1 has value:3 array location:1 has value:4 Matrix no:1 array location:0 has value:5 array location:0 has value:6 array location:1 has value:7 array location:1 has value:8

By using three dimensional array, the elements were stored in two 2*2 matrices in the above program.