All Repeated Words In Text File And Their Occurrences In Java

Find All Repeated Words In Text File And Their Occurrences In Java

Place your file location in the argument of the FileReader.

If the input text file contain :


Details
Name = Amit 
Address = Bangalore
Name = Anuj
Address = Bangalore

The output will be look like

 The string --> Details <-- repeated 1

The string --> Address <-- repeated 2
The string --> Amit <-- repeated 1
The string --> = <-- repeated 4
The string --> Anuj <-- repeated 1
The string --> Name <-- repeated 2
The string --> Bangalore <-- repeated 2


import java.io.BufferedReader;
import java.util.HashMap;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;
public class RepeatedWordInFile {
    public static void main(String[] args)
    {
        BufferedReader br=null;
        try
        {
         br = new BufferedReader(new FileReader("G:\\my.txt"));
            HashMap<String,Integer> myhashmap = new HashMap<String,Integer>();
            String str;
            while((str=br.readLine())!=null)
            {               
            String[] splitstring=str.split(" ");
            for(String allstr:splitstring)
            {
                if(!myhashmap.containsKey(allstr))
                {
                    myhashmap.put(allstr,1);
                }
                else
                {
                     myhashmap.put(allstr,myhashmap.get(allstr)+1);
                }
            }
            }
            
            Set<String> myset=myhashmap.keySet();
            for(String strng:myset)
            {
 System.out.println("The string -->"+" "+strng+" "+"<-- repeated"+" "+myhashmap.get(strng));
            }
        }
        catch(IOException e)
       {
                e.printStackTrace();    
       }
      finally
      {
          try
          {
           br.close();   
          }
          catch(IOException e)
          {
              e.printStackTrace();
          }
                         
      }
               
    }
    
}

Longest Substring Without Repeating Characters In Java time complexity O(n)

Longest Substring Without Repeating Characters In Java time complexity O(n) 
If you try to solve this using HashMap than you will able to find the correct answer but the order of the string would not be same as input string. So you have to used the LinkedHashMap which preserves the insertion order. 
.

import java.util.Scanner;
import java.util.LinkedHashMap;

public class String7_for_blog
{
public static void main(String[] args)
{

int i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your string");
String str=sc.nextLine();
char[] astr=str.toCharArray();
int sublen=0;
String substr=null;
LinkedHashMap<Character,Integer> mymap= new LinkedHashMap<Character,Integer>();
for(i=0;i<astr.length;i++)
{
if(!mymap.containsKey(astr[i]))
{
mymap.put(astr[i],i);
}
else
{
i=mymap.get(astr[i]);
mymap.clear();
}
if(mymap.size()>sublen)
{
sublen=mymap.size();
substr=mymap.keySet().toString();
System.out.println(substr);

}

System.out.println("The input string is =>"+str);
 System.out.println("the length of longest sub-string without repeatation is=>"+""+sublen);
System.out.println("The longest sub-string without repeatation is =>"+substr);
}

}

Lowest Common Ancestor in a Binary Search Tree

Lowest Common Ancestor in a Binary Search Tree

Here the lowest common ancestor of 12 and 14 is 13 , lca of 1 and 13 is 10 so on . 

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

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;

void create()
{
    int data;

    printf("Enter data of node to be inserted : ");
    scanf("%d", &data);
    temp = (struct btnode *)malloc(1*sizeof(struct btnode));
    temp->value = data;
    temp->l = temp->r = NULL;
}


void search(struct btnode *t)
{
    if ((temp->value > t->value) && (t->r != NULL))
        search(t->r);
    else if ((temp->value > t->value) && (t->r == NULL))
        t->r = temp;
    else if ((temp->value < t->value) && (t->l != NULL))
        search(t->l);
    else if ((temp->value < t->value) && (t->l == NULL))
        t->l = temp;
}
void insert()
{
    create();
    if (root == NULL)
        root = temp;
    else
        search(root);
}

void inorder(struct btnode *t)
{
    if (root == NULL)
    {
        printf("No elements in a tree to display");
        return;
    }
    if (t->l != NULL)
        inorder(t->l);
    printf("%d -> ", t->value);
    if (t->r != NULL)
        inorder(t->r);
}
int size(struct btnode* root)
{
    if(root->l==NULL&& root->r==NULL)
        return 1;
    if(root->l!=NULL && root->r==NULL)
        return 1+size(root->l);
    if(root->r!=NULL && root->l==NULL)
        return 1+size(root->r);

  return (size(root->l)+size(root->r))+1;
}

void lowest_common_ancestor(struct btnode* root,int n1,int n2)
{
     if(root->value>n1 && root->value>n2)
    {
        lowest_common_ancestor(root->l,n1,n2);
    }
    if(root->value<n1 && root->value<n2)
    {
        lowest_common_ancestor(root->r,n1,n2);
    }
    if((root->value)<n2 && (root->value)>n1)
    {
        printf("Lowest Common ancestor is %d",root->value);
    }


}

int main()
{
    int ch;
    int a1,a2,num;
    while(1)
    {
    printf("\n");
    printf("OPERATIONS ---\n");
    printf("1.Insert an element into tree\n");
    printf("2.Inorder Traversal\n");
    printf("3.Lowest common Ancestor \n");
    printf("4 Exit\n");
    printf("Enter your choice : ");
    scanf("%d", &ch);
        switch (ch)
        {
        case 1:
            insert();
            break;
        case 2:
            inorder(root);
            break;
        case 3:
            printf("Enter the 2 nodes who's lowest ancestor has to found\n");
            scanf("%d",&a1);
            scanf("%d",&a2);
            lowest_common_ancestor(root,a1,a2);
            break;
        case 4:
            exit(0);
        default :
            printf("Wrong choice, Please enter correct choice  ");
            break;
        }
    }

    return 0;
}




The sum of path of all leaf nodes

Root to leaf path sum equal to a given number



we have to calculate the path sum means the sum of each node in the path for every leaf node.
ex- 
leaf node 1 is having path 15>10>1 so sum is 26
leaf node 14 is having path 15>10>13>14 so sum is 52 


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

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;

void create()
{
    int data;

    printf("Enter data of node to be inserted : ");
    scanf("%d", &data);
    temp = (struct btnode *)malloc(1*sizeof(struct btnode));
    temp->value = data;
    temp->l = temp->r = NULL;
}


void search(struct btnode *t)
{
    if ((temp->value > t->value) && (t->r != NULL))
        search(t->r);
    else if ((temp->value > t->value) && (t->r == NULL))
        t->r = temp;
    else if ((temp->value < t->value) && (t->l != NULL))
        search(t->l);
    else if ((temp->value < t->value) && (t->l == NULL))
        t->l = temp;
}
void insert()
{
    create();
    if (root == NULL)
        root = temp;
    else
        search(root);
}

void inorder(struct btnode *t)
{
    if (root == NULL)
    {
        printf("No elements in a tree to display");
        return;
    }
    if (t->l != NULL)
        inorder(t->l);
    printf("%d -> ", t->value);
    if (t->r != NULL)
        inorder(t->r);
}
int size(struct btnode* root)
{
    if(root->l==NULL&& root->r==NULL)
        return 1;
    if(root->l!=NULL && root->r==NULL)
        return 1+size(root->l);
    if(root->r!=NULL && root->l==NULL)
        return 1+size(root->r);

  return (size(root->l)+size(root->r))+1;
}

int print_root_to_leaf_sum(struct btnode* root, int sum)
{

    if(root->l!=NULL)
    {
        sum=sum+root->value;
        print_root_to_leaf_sum(root->l,sum);
    }

    if(root->r!=NULL)
    {

      print_root_to_leaf_sum(root->r,sum);
       sum=sum+root->value;

    }
    if(root->l==NULL && root->r==NULL)
    {
        sum=sum+root->value;
        printf("the sum of path ==>%d\n",sum);
    }

}


int main()
{
    int ch;
    int a1,a2;
    while(1)
    {
    printf("\n");
    printf("OPERATIONS ---\n");
    printf("1.Insert an element into tree\n");
    printf("2.Inorder Traversal\n");
    printf("3.root to leaf sum\n");
    printf("4 Exit\n");
    printf("Enter your choice : ");
    scanf("%d", &ch);
        switch (ch)
        {
        case 1:
            insert();
            break;
        case 2:
            inorder(root);
            break;
        case 3:
            print_root_to_leaf_sum(root,0);
            break;
        case 4:
            exit(0);
        default :
            printf("Wrong choice, Please enter correct choice  ");
            break;
        }
    }

    return 0;
}



Program to Find the Maximum Depth and Minimum Depth Of a Tree

Program to Find the Maximum Depth and Minimum Depth Of a Tree 




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

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;

void create()
{
    int data;

    printf("Enter data of node to be inserted : ");
    scanf("%d", &data);
    temp = (struct btnode *)malloc(1*sizeof(struct btnode));
    temp->value = data;
    temp->l = temp->r = NULL;
}


void search(struct btnode *t)
{
    if ((temp->value > t->value) && (t->r != NULL))
        search(t->r);
    else if ((temp->value > t->value) && (t->r == NULL))
        t->r = temp;
    else if ((temp->value < t->value) && (t->l != NULL))
        search(t->l);
    else if ((temp->value < t->value) && (t->l == NULL))
        t->l = temp;
}
void insert()
{
    create();
    if (root == NULL)
        root = temp;
    else
        search(root);
}

void inorder(struct btnode *t)
{
    if (root == NULL)
    {
        printf("No elements in a tree to display");
        return;
    }
    if (t->l != NULL)
        inorder(t->l);
    printf("%d -> ", t->value);
    if (t->r != NULL)
        inorder(t->r);
}

int maxDepth(struct btnode* root)
{
    if(root->l==NULL && root->r==NULL)
    {
        return 1;
    }
    if(root->l!=NULL && root->r==NULL)
    {
        return 1+maxDepth(root->l);
    }
    if(root->r!=NULL && root->l==NULL)
    {
        return 1+maxDepth(root->r);
    }

if(maxDepth(root->l)>maxDepth(root->r))
{
    return maxDepth(root->l)+1;
}
else
{
    return maxDepth(root->r)+1;
}

}

int minDepth(struct btnode *root)
{

    if (root == NULL)
        return 0;

    if (root->l == NULL && root->r == NULL)
       return 1;
    if (root->r!=NULL && root->l==NULL)
       return minDepth(root->r) + 1;

    if (root->l!=NULL && root->r==NULL)
       return minDepth(root->l) + 1;


    if(minDepth(root->l)> minDepth(root->r))
       {
           return (minDepth(root->r)+1);
       }
       else
       {
            return (minDepth(root->l)+1);
       }
}


int main()
{
    int ch;
    int a1,a2;
    while(1)
    {
    printf("\n");
    printf("OPERATIONS ---\n");
    printf("1.Insert an element into tree\n");
    printf("2.Inorder Traversal\n");
    printf("3.Min Depth of a tree\n");
    printf("4.max Depth of a tree\n");
    printf("5 Exit\n");
    printf("Enter your choice : ");
    scanf("%d", &ch);
        switch (ch)
        {
        case 1:
            insert();
            break;
        case 2:
            inorder(root);
            break;
        case 3:
            printf("%d",minDepth(root));
            break;
        case 4:
            printf("%d",maxDepth(root));
            break;
        case 5:
            exit(0);
        default :
            printf("Wrong choice, Please enter correct choice  ");
            break;
        }
    }

    return 0;
}


Nth node from the end of a Linked List in one Traversal (Idea Shubham Jaiswal) O(n)

Nth node from the end of a Linked List in one Traversal
time complexity O(n)

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

struct node

{
    char data;
    struct node *next;
}*head;

void insert(int num)

{
    struct node* temp;
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=num;
    temp->next=NULL;
    if(head==NULL)
    {
        head=temp;
    }
    else
    {
        struct node* temp1=head;
        while(temp1->next!=NULL)
        {
            temp1=temp1->next;
        }
        temp1->next=temp;
    }
}


int delete(int num)

{
    struct node *temp,*prev;
    temp=head;
    while(temp!=NULL)
    {

        if(temp->data==num)

        {
            if(temp==head)
            {
                head=temp->next;
                free(temp);
                return 1;
            }
            else
            {
                printf("else Part 1/n");
                prev->next=temp->next;
                free(temp);
                return 1;
            }

        }

        else
        {
            printf("else Part 2/n");
            prev=temp;
            temp=temp->next;
        }
    }
    return 0;
}

void display()

{
    struct node *temp2;
    temp2=head;
    while(temp2!=NULL)
    {
        printf("%d ",temp2->data);
        temp2=temp2->next;

    }


}


void fromlast(int n)

{
    int i;

    struct node* temp=head;

    struct node* start=head;
    for(i=0;i<n;i++)
    {
        temp=temp->next;
    }
    while(temp!=NULL)
    {
        start=start->next;
        temp=temp->next;

    }

    printf("%d",start->data);
}

int  main()

{
    int i,num;
    int pos;
    int n1,n2;
    struct node *n;
    head=NULL;
    while(1)
    {
    printf("\nList Operations\n");
    printf("===============\n");
    printf("1.Insert\n");
    printf("2.Display\n");
    printf("3.Delete\n");
    printf("4.Nth node from the end\n");
    printf("5.Exit\n");

    printf("Enter your choice : ");

    if(scanf("%d",&i)<=0){
        printf("Enter only an Integer\n");
        exit(0);
    } else {
        switch(i)
        {
        case 1:
            printf("Enter the number to insert : ");
                 scanf("%d",&num);
                 insert(num);
                 break;
        case 2:
            if(head==NULL)
                {
                printf("List is Empty\n");
                }
                else
                {
                printf("Element(s) in the list are : ");
                }
                display(n);
                break;
        case 3:
            if(head==NULL)
                printf("List is Empty\n");
                else{
                printf("Enter the number to delete : ");
                scanf("%d",&num);
                if(delete(num))
                    printf("%d deleted successfully\n",num);
                else
                    printf("%d not found in the list\n",num);
                }
                break;
        case 4:
            printf("Nth node from the end \n");
            scanf("%d",&n);
            fromlast(n);
            break;
        case 5:
            exit(1);
        }

    }


    }

return 0;
}

Check for balanced parentheses in an expression in C

Check for balanced parentheses in an expression in C
clear printing steps


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

struct Stack
{
    int top;
    int capacity;
    int* array;

};
struct Stack* createStack( int capacity )
{
    struct Stack* stack=(struct Stack*)malloc(sizeof(struct Stack));
    if(!stack)
    {
        return NULL;
    }
    stack->top=-1;
    stack->capacity=capacity;
    stack->array=(int*)malloc(sizeof(int)*stack->capacity);
    if(!stack->array)
        return NULL;

    return stack;
};
void push(struct Stack* stack, char op)
{
        stack->array[++stack->top]=op;
}
int isEmpty(struct Stack* stack)
{
    return stack->top == -1 ;
}
char pop(struct Stack* stack)
{
    if (!isEmpty(stack))
        return stack->array[stack->top--] ;
    return '$';
}

int check_if(char ob,char cb)
{
    if((ob=='(' && cb==')') || (ob=='{' && cb=='}') || (ob=='[' && cb==']') )
        {
            return 1;
        }
        else
        {
            return 0;
        }
}
void pranbal(char* exp)
{
    int i,j,sum;
    struct Stack* stack=createStack(strlen(exp));
    if(!stack)
        return -1;
    for(i=0;exp[i];i++)
    {
        if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[')
            {
                push(stack,exp[i]);
                printf("this %c is pushed\n",exp[i]);
            }
        if(exp[i]==')'|| exp[i]=='}' || exp[i]==']')
        {
            char ob=pop(stack);
            printf("the combo %c %c\n",ob,exp[i]);
            if(!check_if(ob,exp[i]))
            {
                printf("Unbalanced\n");
                exit(0);
            }
        }
    }
    if(isEmpty(stack))
    {
        printf("Balanced Parenthesis\n");
    }
    else
    {
        printf("Unbalanced Parenthesis\n");
    }
}

int main()
{
    char exp[100];
    printf("Enter the elements\n");
    scanf("%s",exp);
    pranbal(exp);
return 0;
}


Find Itinerary from a given list of tickets HashMap Java O(n)

Find Itinerary from a given list of tickets HashMap Java O(n)


The cities joining each other is given, and you have to find the initial and final  cities along with the cities between them.

The cities joining each other is :
 "Chennai", "Banglore"
 "Bombay", "Delhi"     
 "Goa", "Chennai"
 "Delhi", "Goa"

Now find the starting point of the cities joining which will present in only left side of the data given  
and then traverse the whole data from that starting point , we will get the result. 


import java.util.*;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;

public class Tickets
{

 int i,j,k,l;
 public static void main(String[] args) 
 {
  HashMap<String,String> ticket= new HashMap<String,String>();
  Set<Entry<String,String>> keyValueSet=ticket.entrySet();

  ticket.put("Chennai", "Banglore");
        ticket.put("Bombay", "Delhi");
        ticket.put("Goa", "Chennai");
        ticket.put("Delhi", "Goa");

        HashMap<String, String> reverse = new HashMap<String,String>();

        
        
        String initial=null;
        for(Entry<String,String> entry : keyValueSet)
        {
         reverse.put(entry.getValue(),entry.getKey());
        }  
        for(Entry<String,String> entry : keyValueSet)
        {
         if(!reverse.containsKey(entry.getKey()))
         {
          System.out.println("The starting point:"+entry.getKey());
           initial=entry.getKey();
         }
        } 

        String finalp = ticket.get(initial);

        while (finalp != null)
        {
            System.out.print(initial +  "->" + finalp + ", ");
            initial = finalp;
            finalp = ticket.get(finalp);
        } 
       

 }


}

implement of two stacks in an array in C time complexity O(1)

implement of  two stacks in an array in C

time complexity O(1) 




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

struct Stack
{
    int top1;
    int top2;
    int capacity;
    int* array;

};


void push1(struct Stack* stack,int num)
{
    //printf("%d %d\n",stack->top1,stack->top2);
    if(stack->top2-stack->top1==1)
    {
        printf("Stack Overflow");
         exit(1);
    }
    else
    {
    stack->array[++stack->top1]=num;

    }
    //printf("%d %d\n",stack->top1,stack->top2);
}

void push2(struct Stack* stack,int num)
{
if(stack->top2-stack->top1==1)
{
      printf("Stack Overflow");
 exit(1);
}
   else
    {
    stack->array[--stack->top2]=num;

    }
    //printf("%d %d\n",stack->top1,stack->top2);
}
int pop1(struct Stack* stack)
{
    return stack->array[stack->top1--];
}
int pop2(struct Stack* stack)
{
    return stack->array[stack->top2++];
}
int main()
{
    int i,j,k,l,m,num,n;
    printf("Enter the capacity of the stack\n");
    scanf("%d",&m);
    struct Stack* stack=(struct Stack*)malloc(sizeof(struct Stack));
    stack->top1=-1;
    stack->top2=m;
    stack->capacity=m;
    stack->array=(int*)malloc(sizeof(int)*stack->capacity);

    while(1)
    {
     printf("1. Enter the elements in the stack1\n");
     printf("2. Enter the elements in the stack2\n");
     printf("3. Pop the elements from the stack1\n");
     printf("4. Pop the elements from the stack2\n");
     printf("5. Exit\n");
     scanf("%d",&n);
     switch(n)
     {
     case 1:
        printf("Enter the elements you want to enter in the stack1=");
        scanf("%d",&num);
        push1(stack,num);
        break;
     case 2:
        printf("Enter the elements you want to enter in the stack2=");
        scanf("%d",&num);
        push2(stack,num);
        break;
     case 3:
        printf("%d is poped from stack1\n",pop1(stack));
        break;
     case 4:
        printf("%d is poped from stack2\n",pop2(stack));
        break;
     case 5:
        exit(0);


     }
    }
return 0;
}


Write a Java program which implements LinkedList as a Queue (FIFO)

 Write a Java program which implements LinkedList as a Queue (FIFO)

The two methods offer() and poll()  makes LinkedList to work as a Queue.

import java.util.LinkedList;
import java.util.Scanner;

public class LinkedListAsQueue
{
    public static void main(String[] args)
    {
        int i;
        Scanner sc = new Scanner(System.in);
        LinkedList<Integer> mylist= new LinkedList<Integer>();
        while(true)
        {
            System.out.println("1.Insert in linked list");
            System.out.println("2.Dequeue the linked list FIFO");
            System.out.println("3.exit\n");
            int num= sc.nextInt();
            switch(num)
            {
            case 1:
                System.out.println("Insert the number  in the linked list=>");
                int n=sc.nextInt();
                mylist.add(n);
                break;
            case 2:
            System.out.println("Dequeue the linked list FIFO using default method =>"+mylist.poll());  
            break;
            case 3:
            System.exit(0);
            default:
                System.out.println("Wrong choice\n");

                
            }
            

        }
    }
} 

Find the first repeating element in an array of integers time complexity O(n)

Find the first repeating element in an array of integers

Time Complexity O(n)


This problem can be solved by the vector also the only difference is that you have to replace the add method with the addElement() method and import Vector.

The only main difference between the ArrayList and Vector is that Vector is thread safe but the ArrayList is not.

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class ArrayList1
{
public static void main(String[] args) 
{
int i;
int [] arr=new int[30];
System.out.println("Enter the size of the array\n");
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
for(i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
ArrayList <Integer> al= new ArrayList<Integer>();

for(i=0;i<n;i++)
{
if(al.contains(arr[i]))
{
System.out.println("The first repeated element in the array is "+arr[i]); 
                                 break;

}
else
{
al.add(arr[i]);
}
}

}

}

Remove duplicates from an unsorted linked list 0(n)

Remove duplicates from an unsorted linked list

time complexity O(n) 


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

struct node
{
    char data;
    struct node *next;
}*head;



void insert(int num)
{
    struct node* temp;
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=num;
    temp->next=NULL;
    if(head==NULL)
    {
        head=temp;
    }
    else
    {
        struct node* temp1=head;
        while(temp1->next!=NULL)
        {
            temp1=temp1->next;
        }
        temp1->next=temp;
    }
}
void display()
{
    struct node *temp2;
    temp2=head;
    while(temp2!=NULL)
    {
        printf("%d ",temp2->data);
        temp2=temp2->next;

    }

}

void remove_the_duplicate_elements_from_the_linked_list()
{
    struct node* temp=head;
    struct node* prev=NULL;
    std::set<int> checklist;
    std::set<int>::iterator it;
    while(temp!=NULL)
    {


        if(checklist.find(temp->data)==checklist.end())
        {
                checklist.insert(temp->data);
                prev=temp;

        }
        else
        {
            if(checklist.find(temp->data)!=checklist.end())
            {
                    prev->next=temp->next;
                    free(temp);
            }
        }
        temp=temp->next;

    }

}

int  main()
{
    int i,num;
    int pos;
    int n1,n2;
    struct node *n;
    head=NULL;
    while(1)
    {
    printf("\nList Operations\n");
    printf("===============\n");
    printf("1.Insert\n");
    printf("2.Display\n");
    printf("3. Delete the duplicate elements from a linked list\n");
     printf("4.Exit\n");

    printf("Enter your choice : ");
    if(scanf("%d",&i)<=0){
        printf("Enter only an Integer\n");
        exit(0);
    } else {
        switch(i)
        {
        case 1:      printf("Enter the number to insert : ");
                 scanf("%d",&num);
                 insert(num);
                 break;
        case 2:     if(head==NULL)
                {
                printf("List is Empty\n");
                }
                else
                {
                printf("Element(s) in the list are : ");
                }
                display();
                break;
        case 3:
            if(head==NULL)
            {
                printf("List is Empty\n");
            }
            else
            {
                printf("Deleting the duplicate elements from the linked list\n");
                remove_the_duplicate_elements_from_the_linked_list();
                printf("Elements removed\n");
            }

            break;
        case 4:
            return 0;


        default:    printf("Invalid option\n");
        }
    }
}
}

Check if a number is even or odd without using any arithmetic operator. easy but tricky one :-)

Check if a number is even or odd without using any arithmetic operator



#include<stdio.h>
int main()
{
    int i,j,k,l;
    int n;
    printf("Enter the number to be checked even or odd\n");
    scanf("%d",&n);

    if((n&1)==0)
    {
        printf("This is even number\n");

    }
    else
    {
        printf("This is odd number\n");
    }
    return 0;

}

Detect loop in a linked list O(n)

Detect loop in a linked list

time complexity O(n)

What I have done is take a set then insert the addresses of each node in the set so if there will be loop in the linked list then address that has to be insert will detect second time .

The method to detect the loop is pretty straightforward but the length of the code is more than it has to be because I added an extra function that allows you to create the loop by selecting the position where you want to create the loop.

create_loop_in_a_linked_list(n1,n2) is the  extra function in this function you have to provide two values the data for the new node and the position where you have to create loop.
After creating your loop you can check from the function Detect_loop_in_a_linked_list().

if you apply Detect_loop_in_a_linked_list() without creating the loop in the linked list then it will gave an output as no loop in the linked  list.

we can also find the position where the loop is found .The code will be update soon..




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

using namespace std;

struct node
{
    char data;
    struct node *next;
}*head;



void insert(int num)
{
    struct node* temp;
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=num;
    temp->next=NULL;
    if(head==NULL)
    {
        head=temp;
    }
    else
    {
        struct node* temp1=head;
        while(temp1->next!=NULL)
        {
            temp1=temp1->next;
        }
        temp1->next=temp;
    }
}

void create_loop_in_a_linked_list(int num,int n2)
{
    int i;
    struct node* temp;
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=num;
    struct node* temp1=head;
    while(temp1->next!=NULL)
    {
     temp1=temp1->next;
    }
    temp1->next=temp;

    struct node* temp2=head;
    for(i=0;i<n2;i++)
    {
        temp2=temp2->next;
    }
    temp->next=temp2;


}

void display()
{
    struct node *temp2;
    temp2=head;
    while(temp2!=NULL)
    {
        printf("%d ",temp2->data);
        temp2=temp2->next;

    }

}



int Detect_loop_in_a_linked_list()
{


    std::set<node*> check_loop;
    std::set<node*>::iterator it;
    struct node* temp=head;
    check_loop.insert(temp);
    temp=temp->next;


    while(temp!=NULL)
    {
        if(check_loop.find(temp)!=check_loop.end())
        {
            return 1;
        }
        check_loop.insert(temp);
        temp=temp->next;
    }
    return 0;
}

int  main()
{
    int i,num;
    int pos;
    int n1,n2;
    struct node *n;
    head=NULL;
    while(1)
    {
    printf("\nList Operations\n");
    printf("===============\n");
    printf("1.Insert\n");
    printf("2.Display\n");
    printf("3.create a loop in a linked list by inserting at last and pointing it to any previous element\n");
    printf("4.detect a loop\n");
     printf("5.Exit\n");

    printf("Enter your choice : ");
    if(scanf("%d",&i)<=0){
        printf("Enter only an Integer\n");
        exit(0);
    } else {
        switch(i)
        {
        case 1:      printf("Enter the number to insert : ");
                 scanf("%d",&num);
                 insert(num);
                 break;
        case 2:     if(head==NULL)
                {
                printf("List is Empty\n");
                }
                else
                {
                printf("Element(s) in the list are : ");
                }
                display();
                break;

        case 3:
            printf("Enter the element and the position where the loop has to be made\n");
            scanf("%d %d",&n1,&n2);
            create_loop_in_a_linked_list(n1,n2);
            break;
        case 4:
            if(Detect_loop_in_a_linked_list())
                printf("Loop detected\n");
            else
            printf("No loop detected\n");
            break;

        case 5:
            return 0;


        default:    printf("Invalid option\n");
        }
    }
}

return 0;
}

All Repeated Words In Text File And Their Occurrences In Java

Find All Repeated Words In Text File And Their Occurrences In Java Place your file location in the argument of the FileReader. If t...