Wednesday, December 4, 2002

T R A N S P O S E A M A T R I X

package org.interview.test;

import java.util.Scanner;

/**
 * This code can be used to check if a matrix symmetric or not, 
 * just compare the matrix with it's transpose if they are same then it's 
 * symmetric otherwise non symmetric, also it's useful for calculating 
 * orthogonality of a matrix.
 * @author ADixit3034C
 *
 */
public class TransposeAMatrix {

public static void main(String args[])
  {
     int m, n, c, d;
 
     Scanner in = new Scanner(System.in);
     System.out.println("Enter the number of rows and columns of matrix");
     m = in.nextInt();
     n = in.nextInt();
 
     int matrix[][] = new int[m][n];
 
     System.out.println("Enter the elements of matrix");
 
     for ( c = 0 ; c < m ; c++ )
        for ( d = 0 ; d < n ; d++ )
           matrix[c][d] = in.nextInt();
 
     int transpose[][] = new int[n][m];
 
     for ( c = 0 ; c < m ; c++ )
     {
        for ( d = 0 ; d < n ; d++ )               
           transpose[d][c] = matrix[c][d];
     }
 
     System.out.println("Transpose of entered matrix:-");
 
     for ( c = 0 ; c < n ; c++ )
     {
        for ( d = 0 ; d < m ; d++ )
              System.out.print(transpose[c][d]+"\t");
 
        System.out.print("\n");
     }
  }
}

Tuesday, December 3, 2002

SWAP NUMBERS

package org.interview.test;

import java.util.Scanner;

public class SwapNumbers {

public static void main(String args[])
  {
swapNumberTemp();
swapNumWithOutTempVar();
  }

public static void swapNumWithOutTempVar () {
int x, y;
     System.out.println("Enter x and y");
     Scanner in = new Scanner(System.in);
 
     x = in.nextInt();
     y = in.nextInt();
 
     System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
 
     x = x + y;
     y = x - y;
     x = x - y;
 
     System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}

public static void swapNumberTemp(){
     int x, y, temp;
     System.out.println("Enter x and y");
     Scanner in = new Scanner(System.in);
 
     x = in.nextInt();
     y = in.nextInt();
 
     System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
 
     temp = x;
     x = y;
     y = temp;
 
     System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}

}

R E V E R S E A N U M B E R

package org.interview.test;

import java.util.Scanner;

public class ReverseANumber {

public static void main(String args[])
  {
     int n, reverse = 0;
 
     System.out.println("Enter the number to reverse");
     Scanner in = new Scanner(System.in);
     n = in.nextInt();
 
     while( n != 0 )
     {
         reverse = reverse * 10;
         reverse = reverse + n%10;
         n = n/10;
     }
 
     System.out.println("Reverse of entered number is "+reverse);
  }

}

P R I N T A L P H A B E T S

package org.interview.test;

public class PrintAlphabets {

public static void main(String [] args) throws Exception {
char x = 'a';

for (x ='a'; x <= 'z' ; x++) {
System.out.print(x);
}
System.out.println();

char y = 'a';
while (y <= 'z') {
System.out.print(y);
y++;
}

System.out.println();

char c = 'a';
do {
System.out.print(c);
c++;
} while (c <= 'z');
}
}

L I N E A R S E A R C H

package org.interview.test;

import java.util.Scanner;

/**
 * Above code locate first instance of element to found, you can modify it for multiple 
 * occurrence of same element and count how many times it occur in the list. 
 * Similarly you can find if an alphabet is present in a string.
 *
 */
public class LinearSearch {

public static void main (String [] args) throws Exception {
int c, n, search, array[];
 
   Scanner in = new Scanner(System.in);
   System.out.println("Enter number of elements");
   n = in.nextInt(); 
   array = new int[n];
 
   System.out.println("Enter " + n + " integers");
 
   for (c = 0; c < n; c++)
     array[c] = in.nextInt();
 
   System.out.println("Enter value to find");
   search = in.nextInt();
 
   for (c = 0; c < n; c++)
   {
     if (array[c] == search)     /* Searching element is present */
     {
        System.out.println(search + " is present at location " + (c + 1) + ".");
         break;
     }
  }
  if (c == n)  /* Searching element is absent */
     System.out.println(search + " is not present in array.");
}
}

Monday, December 2, 2002

S Y S T E M C O M M A N D S

package org.interview.test;

import java.net.InetAddress;
import java.util.Random;

public class SystemCommands {

public static void main (String [] args) throws Exception {
Runtime rt = Runtime.getRuntime();
//rt.exec("notepad");
//rt.exec("mspaint");

System.out.println("Free memory in JVM before Garbage Collection = "+rt.freeMemory());
   rt.gc();
   System.out.println("Free memory in JVM after Garbage Collection = "+rt.freeMemory());
     System.out.println(InetAddress.getLocalHost());
     
     int c;
     Random t = new Random();
  
     // random integers in [0, 100]
  
     for (c = 1; c <= 10; c++) {
       System.out.println(t.nextInt(100));
     }
     
}
}

P A L I N D R O M E

package org.interview.test;

import java.util.Scanner;

public class Palindrome {

public static void main(String [] args) throws Exception {
String original , reverse = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter:" );
original = sc.next();

int length = original.length();

System.out.println("Length:"+length);

for(int i =length-1; i >= 0; i--) {
reverse = reverse + original.charAt(i);
}

System.out.println("Reverse:"+ reverse);

if(original.equals(reverse)) {
System.out.println(original+" - is palindrome of - " + reverse);
}
}

}
= = = = = = = = = = = = = = = = = Reverse String recursive and iterative = = = = = = = = = = = = = = = = = = = = = 
package com.test;

import java.io.FileNotFoundException;
import java.io.IOException;

public class StringReverseExample {

    public static void main(String args[]) throws FileNotFoundException, IOException {

        //original string
        String str = "Sony is going to introduce Internet TV soon";
        System.out.println("Original String: " + str);

        //reversed string using Stringbuffer
        String reverseStr = new StringBuffer(str).reverse().toString();
        System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);

        //iterative method to reverse String in Java
        reverseStr = reverse(str);
        System.out.println("Reverse String in Java using Iteration: " + reverseStr);

        //recursive method to reverse String in Java
        reverseStr = reverseRecursively(str);
        System.out.println("Reverse String in Java using Recursion: " + reverseStr);

    }

    public static String reverse(String str) {
        StringBuilder strBuilder = new StringBuilder();
        char[] strChars = str.toCharArray();

        for (int i = strChars.length - 1; i >= 0; i--) {
            strBuilder.append(strChars[i]);
        }

        return strBuilder.toString();
    }

    public static String reverseRecursively(String str) {

        //base case to handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }

        return reverseRecursively(str.substring(1)) + str.charAt(0);

    }
}

P R I M E N U M B E R

package org.interview.test;

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

public class PrimeNumbers {


public static void main(String [] args) throws Exception {
PrimeNumbers pn = new PrimeNumbers();
int number =18;
List<Integer> l = new ArrayList<Integer>();
for(int i=2; i< number; i++){
if(pn.isPrime(i)) {
l.add(i);
}
}
System.out.println("IsPrime:" + l);


}


// Find prime number from a number.
public boolean isPrime(int number) {
for (int i=2; i< number; i++){
if(number%i == 0){
return false;
}
}
return true;
}

}

Largest Number

package org.interview.test;

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

public class LargestNumber {

public static void main (String [] args ) throws Exception {

List<Integer> il = new ArrayList<Integer>();

Scanner sc = new Scanner(System.in);

int i;
do{
i  = sc.nextInt();
il.add(i);
} while (i != -1);
System.out.println("List:"+il);

for (int in : il) {
if (in > i)
i = in;
}

System.out.println("Largest Number:"+ i);


}
}

Floyd Triangle

package org.interview.test;

import java.util.Scanner;

public class FloydTriangle {

/*
*In Floyd triangle there are n integers in the nth row and a total of (n(n+1))/2 integers 
*in n rows. This is a simple pattern to print but helpful in learning how to create other 
*patterns. Key to develop pattern is using nested loops appropriately.
*/
public static void main (String [] args) throws Exception {
int n, num = 1, c, d;
     Scanner in = new Scanner(System.in);
 
     System.out.println("Enter the number of rows of floyd's triangle you want");
     n = in.nextInt();
 
     System.out.println("Floyd's triangle :-");
 
     for ( c = 1 ; c <= n ; c++ )
     {
        for ( d = 1 ; d <= c ; d++ )
        {
           System.out.print(num+" ");
           num++;
        }
 
        System.out.println();
     }
}
}

F A C T O R I A L

package org.interview.test;

import java.util.Scanner;

public class Factorial {

public static void main (String [] args) throws Exception {
findFactorial();
}

public static Integer findFactorial() {
 int n , fact = 1;
 
 Scanner sc = new Scanner(System.in);
 
 System.out.println("Enter number to calculate Factorial: ");
 n = sc.nextInt();
 
 for (int i = 1 ; i <= n ; i++) {
 fact *= i;
 }
 System.out.println("Factorial: " + fact);
 return fact;
}

}

C A L C U L A T O R

package org.interview.test;

import java.util.Scanner;

public class Calculator {

public static void main (String []  args) throws Exception {

Scanner sc = new Scanner(System.in);

System.out.println("First Number:");
int x = sc.nextInt();
System.out.println("Second Number:");
int y = sc.nextInt();

System.out.println("Mathematical Operation:");
String op = sc.next();

if(op.equalsIgnoreCase("/")) {
System.out.println(x/y);
}else if(op.equalsIgnoreCase("*")) {
System.out.println(x*y);
}else if(op.equalsIgnoreCase("+")) {
System.out.println(x+y);
}else if(op.equalsIgnoreCase("-")) {
System.out.println(x-y);
}else if(op.equalsIgnoreCase("eo")) {
if(x%2==0) {
System.out.print("X is Even");
} else {
System.out.println("X is Odd");
}
if(y%2==0) {
System.out.print("Y is Even");
} else {
System.out.println("Y is Odd");
}
}

}
}

Sunday, December 1, 2002

Bubble Sort

package org.interview.test;

import java.util.Scanner;

public class BubbleSort {

/**
* Complexity of bubble sort is O(n2) which makes it a less frequent option for 
* arranging in sorted order when quantity of numbers is high.
* @param args
*/
public static void main(String []args) {
   int n, c, d, swap;
   Scanner in = new Scanner(System.in);
 
   System.out.println("Input number of integers to sort");
   n = in.nextInt();
 
   int array[] = new int[n];
 
   System.out.println("Enter " + n + " integers");
 
   for (c = 0; c < n; c++) 
     array[c] = in.nextInt();
 
   for (c = 0; c < ( n - 1 ); c++) {
     for (d = 0; d < n - c - 1; d++) {
       if (array[d] > array[d+1]) /* For descending order use < */
       {
         swap       = array[d];
         array[d]   = array[d+1];
         array[d+1] = swap;
       }
     }
   }
 
   System.out.println("Sorted list of numbers");
 
   for (c = 0; c < n; c++) 
     System.out.println(array[c]);
 }

}

Binary Search

package org.interview.test;

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {

public static void main (String [] args) throws Exception {
binarySearch();

binarySearch02();
}



public static void binarySearch02(){


int c, first, last, middle, n, search, array[];
 
   Scanner in = new Scanner(System.in);
   System.out.println("Enter number of elements");
   n = in.nextInt(); 
   array = new int[n];
 
   System.out.println("Enter " + n + " integers");
 
 
   for (c = 0; c < n; c++)
     array[c] = in.nextInt();
 
   System.out.println("Enter value to find");
   search = in.nextInt();
 
   first  = 0;
   last   = n - 1;
   middle = (first + last)/2;
 
   while( first <= last )
   {
     if ( array[middle] < search )
       first = middle + 1;    
     else if ( array[middle] == search ) 
     {
       System.out.println(search + " found at location " + (middle + 1) + ".");
       break;
     }
     else
        last = middle - 1;
 
     middle = (first + last)/2;
  }
  if ( first > last )
     System.out.println(search + " is not present in the list.\n");
  
  
}

/**
* binarySearch method returns the location if a match occurs otherwise -(x+1) 
* where x is the no. of elements in the array, For example in the second case 
* above when p is not present in characters array the returned value will be -6.
*/
public static void binarySearch (){
char characters[] = { 'a', 'b', 'c', 'd', 'e' };
 
   System.out.println(Arrays.binarySearch(characters, 'a'));
   System.out.println(Arrays.binarySearch(characters, 'c'));
   System.out.println(Arrays.binarySearch(characters, 'p'));
}
}

Armstrong Number

package org.interview.test;

import java.util.Scanner;

public class ArmstrongNumber {

/*
* An Armstrong number of three digits is an integer such that the sum of the cubes of its 
*  digits is equal to the number itself. 
* For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.
*/
public static void main (String [] args ) throws Exception {
int n, sum = 0, temp, r;
 
     Scanner in = new Scanner(System.in);
     System.out.println("Enter a number to check if it is an armstrong number");      
     n = in.nextInt();
 
     temp = n;
     System.out.println("temp:"+temp);
     int c =1;
     while( temp != 0 ) {
     System.out.println(c+".temp:"+temp);
        r = temp%10;
        System.out.println(c+".r:"+r);
        sum = sum + r*r*r;
        System.out.println(c+".sum:"+sum);
        temp = temp/10; 
        System.out.println(c+".temp:"+temp);
        c++;
     }
 
     if ( n == sum )
        System.out.println("Entered number is an armstrong number.");
     else
        System.out.println("Entered number is not an armstrong number.");
}

}

Add Matrix

package org.interview.test;

import java.util.Scanner;

public class AddMatrix {
public static void main(String args[])
  {
     int m, n, c, d;
     Scanner in = new Scanner(System.in);
 
     System.out.println("Enter the number of rows and columns of matrix");
     m = in.nextInt();
     n  = in.nextInt();
 
     int first[][] = new int[m][n];
     int second[][] = new int[m][n];
     int sum[][] = new int[m][n];
 
     System.out.println("Enter the elements of first matrix");
 
     for (  c = 0 ; c < m ; c++ )
        for ( d = 0 ; d < n ; d++ )
           first[c][d] = in.nextInt();
 
     System.out.println("Enter the elements of second matrix");
 
     for ( c = 0 ; c < m ; c++ )
        for ( d = 0 ; d < n ; d++ )
           second[c][d] = in.nextInt();
 
     for ( c = 0 ; c < m ; c++ )
        for ( d = 0 ; d < n ; d++ )
            sum[c][d] = first[c][d] + second[c][d];  //replace '+' with '-' to subtract matrices
 
     System.out.println("Sum of entered matrices:-");
 
     for ( c = 0 ; c < m ; c++ )
     {
        for ( d = 0 ; d < n ; d++ )
           System.out.print(sum[c][d]+"\t");
 
        System.out.println();
     }
  }
}

Thursday, June 27, 2002

SSH Passwordless Login Using SSH Keygen in 5 Easy Steps

SSH (Secure SHELL) is an open source and most trusted network protocol that is used to login into remote servers for execution of commands and programs. It is also used to transfer files from one computer to another computer over the network using secure copy (SCP) Protocol.
In this article I will show you how to setup password-less login using ssh keys to connect to remote Linux servers without entering password. Using Password-less login with SSH keys will increase the trust between two Linux servers for easy file synchronization or transfer.
If you are dealing with number of Linux remote servers, then SSH Password-less login is one of the best way to automate tasks such as automatic backups with scripts, synchronization files using scp and remote command execution.
In this example we will setup SSH password-less automatic login from server '192.168.1.1' as user 'anupuser' to '192.168.1.2' with user 'dixituser'.

Step 1: Create Authentication SSH-Kegen Keys on –(192.168.1.1)

First login into server 192.168.1.1 with user anupuser and generate a pair of public keys using following command.
[anupuser@anupuser.com ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/anupuser/.ssh/id_rsa): [Press enter key]
Created directory '/home/anupuser/.ssh'.
Enter passphrase (empty for no passphrase): [Press enter key]
Enter same passphrase again: [Press enter key]
Your identification has been saved in /home/anupuser/.ssh/id_rsa.
Your public key has been saved in /home/anupuser/.ssh/id_rsa.pub.
The key fingerprint is:
af:bc:25:72:d4:04:65:d9:5d:11:f0:eb:1d:89:50:4c anupuser@anupuser.com
The key's randomart image is:

Step 2: Create .ssh Directory on – (192.168.1.2)

Use SSH from server 192.168.1.1 to connect server 192.168.1.2 using dixituser as user and create .ssh directory under it, using following command.
[anupuser@anupuser.com ~]$ ssh dixituser@192.168.1.2 mkdir -p .ssh
The authenticity of host '192.168.1.2 (192.168.1.2)' can't be established.
RSA key fingerprint is d6:53:94:43:b3:cf:d7:e2:b0:0d:50:7b:17:32:29:2a.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.2' (RSA) to the list of known hosts.
dixituser@192.168.1.2's password: [Enter Your Password Here]

Step 3: Upload Generated Public Keys to – 192.168.1.2

Use SSH from server 192.168.1.1 and upload new generated public key (id_rsa.pub) on server 192.168.1.2 under dixituser‘s .ssh directory as a file name authorized_keys.
[anupuser@anupuser.com ~]$ cat .ssh/id_rsa.pub | ssh dixituser@192.168.1.2 'cat >> .ssh/authorized_keys'
dixituser@192.168.1.2's password: [Enter Your Password Here]

Step 4: Set Permissions on – 192.168.1.2

Due to different SSH versions on servers, we need to set permissions on .ssh directory and authorized_keys file.
[anupuser@anupuser.com ~]$ ssh dixituser@192.168.1.2 "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"
dixituser@192.168.1.2's password: [Enter Your Password Here]

Step 5: Login from 192.168.1.1 to 192.168.1.2 Server without Password

From now onwards you can log into 192.168.1.2 as 'dixituser' user from server 192.168.1.1 as 'anupuser' user without password.
[anupuser@anupuser.com ~]$ ssh dixituser@192.168.1.2

Optional Step Four—Disable the Password for Root Login

Once you have copied your SSH keys unto your server and ensured that you can log in with the SSH keys alone, you can go ahead and restrict the root login to only be permitted via SSH keys. In order to do this, open up the SSH config file:
sudo nano /etc/ssh/sshd_config
Within that file, find the line that includes PermitRootLogin and modify it to ensure that users can only connect with their SSH key:
PermitRootLogin without-password
Put the changes into effect:
reload ssh

Monday, April 15, 2002

GCD Greatest Common Divisor

package com.test;

import java.util.Scanner;

public class GCDExample {
 
 
    public static void main(String args[]){
     
        //Enter two number whose GCD needs to be calculated.      
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter first number to find GCD");
        int number1 = scanner.nextInt();
        System.out.println("Please enter second number to find GCD");
        int number2 = scanner.nextInt();
      
        System.out.println("GCD of two numbers " + number1 +" and " 
                           + number2 +" is :" + findGCD(number1,number2));
      
      
    }

    /*
     * Java method to find GCD of two number using Euclid's method
     * @return GDC of two numbers in Java
     */
    private static int findGCD(int number1, int number2) {
        //base case
        if(number2 == 0){
            return number1;
        }
        return findGCD(number2, number1%number2);
    }
  
}

Friday, April 12, 2002

Check Duplicates in Java Array

package com.test;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CheckAllDuplicatesInJavaArray {

    public static void main(String args[])  {
       
       String[] withDuplicates = new String[] {"one","two","three","one"};
        String[] withoutDuplicates = new String[] {"one","two","three"};
      
        System.out.println("Checking array with duplicate using brute force: " + bruteforce(withDuplicates));
        System.out.println("Checking array without any duplicate using brute force: " + bruteforce(withoutDuplicates));
      
        System.out.println("Checking array with duplicate using Set and List: " + checkDuplicateUsingSet(withDuplicates));
        System.out.println("Checking array without any duplicate using Set and List: " + checkDuplicateUsingSet(withoutDuplicates));

      
        System.out.println("Checking array with duplicate using Set and List: " + checkDuplicateUsingAdd(withDuplicates));
        System.out.println("Checking array without any duplicate using Set and List: " + checkDuplicateUsingAdd(withoutDuplicates));

      
    }
  
    /*
     * brute force way of checking if array contains duplicates in Java
     * comparing each elements to all other elements of array
     * complexity on order of O(n^2) not advised in production
     */
    public static boolean bruteforce(String[] input) {
        for (int i = 0; i < input.length; i++) {
            for (int j = 0; j < input.length; j++) {
                if (input[i].equals(input[j]) && i != j) {
                    return true;
                }
            }
        }
        return false;
    }
    /*
     * detect duplicate in array by comparing size of List and Set
     * since Set doesn't contain duplicate, size must be less for an array which contains duplicates
     */
    public static boolean checkDuplicateUsingSet(String[] input){
        List inputList = Arrays.asList(input);
        Set inputSet = new HashSet(inputList);
        if(inputSet.size()< inputList.size()) {
            return true;
        }
        return false;
    }
  
    /*
     * Since Set doesn't allow duplicates add() return false
     * if we try to add duplicates into Set and this property
     * can be used to check if array contains duplicates in Java
     */
    public static boolean checkDuplicateUsingAdd(String[] input) {
        Set tempSet = new HashSet();
        for (String str : input) {
            if (!tempSet.add(str)) {
                return true;
            }
        }
        return false;
    }
}

Sunday, March 3, 2002

Java program to find middle element of linked list in one pass.

 Java program to find middle element of linked list in one pass. 

How do you find middle element of LinkedList in one pass is a programming question often asked to Java and non Java programmers in telephonic Interview. This question is similar to checking palindrome or calculating factorial, where Interviewer some time also ask to write code. In order to answer this question candidate must be familiar with LinkedList data structure i.e. In case of singly LinkedList, each node of Linked List contains data and pointer, which is address of next Linked List and last element of Singly Linked List points towards null. Since in order to find middle element of Linked List you need to find length of LinkedList, which is counting elements till end i.e. until you find the last element on Linked List. What makes this data structure Interview question interesting is that you need to find middle element of LinkedList in one pass and you don’t know length of LinkedList. This is where candidates logical ability puts into test,  whether he is familiar with space and time trade off or not etc. As if you think carefully you can solve this problem by using two pointers as mentioned in my last post on How to find length of Singly Linked List in Java. By using two pointers, incrementing one at each iteration and other at every second iteration. When first pointer will point at end of Linked List, second pointer will be pointing at middle node of Linked List.  In fact this two pointer approach can solve multiple similar problems e.g. How to find 3rd element from last in a Linked List in one Iteration or How to find nth element from last in a Linked List. In this Java programming tutorial we will see a Java program which finds middle element of Linked List in one Iteration.


package com.test;

/**
 * Java program to find middle element of linked list in one pass. In order to
 * find middle element of linked list we need to find length first but since we
 * can only traverse linked list one time, we will use two pointers one which we
 * will increment on each iteration while other which will be incremented every
 * second iteration. so when first pointer will point to the end of linked list,
 * second will be pointing to the middle element of linked list
 * 
 * @author captain
 */
public class LinkedListTest {

public static void main(String args[]) {
// creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
LinkedList.Node head = linkedList.head();
linkedList.add(new LinkedList.Node("1"));
linkedList.add(new LinkedList.Node("2"));
linkedList.add(new LinkedList.Node("3"));
linkedList.add(new LinkedList.Node("4"));

// finding middle element of LinkedList in single pass
LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;

while (current.next() != null) {
length++;
if (length % 2 == 0) {
middle = middle.next();
}
current = current.next();
}

if (length % 2 == 1) {
middle = middle.next();
}

System.out.println("length of LinkedList: " + length);
System.out.println("middle element of LinkedList : " + middle);

}

}

class LinkedList {
private Node head;
private Node tail;

public LinkedList() {
this.head = new Node("head");
tail = head;
}

public Node head() {
return head;
}

public void add(Node node) {
tail.next = node;
tail = node;
}

public static class Node {
private Node next;
private String data;

public Node(String data) {
this.data = data;
}

public String data() {
return data;
}

public void setData(String data) {
this.data = data;
}

public Node next() {
return next;
}

public void setNext(Node next) {
this.next = next;
}

public String toString() {
return this.data;
}
}
}