Find middle element in a linkedlist

Please refer the Linked List code in the below GitHub repo.
https://github.com/dkbalachandar/custom-linkedlist

 

   private void findMiddleElement() {

        //Move by one node at a time
        Node firstPointer = head;
        //Move by two nodes at a time
        Node secondPointer = head;
        while (secondPointer!= null && secondPointer.getNext() != null &&
                secondPointer.getNext().getNext() != null) {
            firstPointer = firstPointer.getNext();
            secondPointer = secondPointer.getNext().getNext();
        }
        System.out.println("Middle Element is: "+ firstPointer.getData());

    }

 

Advertisements

Convert Sorted Array to BST


import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * Convert a sorted array into a Binary Search Tree
 *
 */
public class TreeUtils {

    static class Tree {
        int val;
        Tree left;
        Tree right;

        Tree(int x) {
            val = x;
        }
        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this);
        }
    }

    public static void main(String[] args) {
        int num[] = {1, 2, 3, 4, 5, 6, 7};
        Tree tree = sortedArrayToBST(num, 0, num.length - 1);
        System.out.println(tree);
    }

    public static Tree sortedArrayToBST(int[] num, int start, int end) {
        if (start > end)
            return null;
        int middle= (start + end) / 2;
        Tree root = new Tree(num[middle]);
        root.left = sortedArrayToBST(num, start, middle - 1);
        root.right = sortedArrayToBST(num, middle + 1, end);
        return root;
    }
}

Given a string, calculate the frequency of characters, output the array with the letter and frequency. (such as: for “abbcdc”, the output should be (a,1),(b,2),(c,2),(d,1))



import java.util.LinkedHashMap;
import java.util.Map;


public class StringUtils {

    public static void main(String[] args) {
        String str = "abbcdc";
        Map charFreqMap = new LinkedHashMap();
        char[] charArray = str.toCharArray();
        for (Character ch : charArray) {
            if (charFreqMap.get(ch) != null) {
                charFreqMap.put(ch, charFreqMap.get(ch) + 1);
            } else {
                charFreqMap.put(ch, 1);
            }
        }
        for (Map.Entry mapEntry : charFreqMap.entrySet()) {
            System.out.print("(" + mapEntry.getKey() + "," + mapEntry.getValue() + ")");
            System.out.print(",");
        }
    }
}