I am practicing LinkedList
problems. How do I make it production level code as is mostly expected in a coding interview? Any other Suggestions?
package LinkedList;
/**
* @author Amogh Antarkar
* @email [email protected]
*/
import java.util.*;
public class LinkedList{
public static void main(String[]args){
switchCase();
System.out.println("Successful completion of the LinkedList program");
}
/* Note: Here a singleton pattern has been used for the Scanner in
* as only one instance is created during the entire implementation
*/
public static void switchCase(){
int cont;
Scanner in = new Scanner(System.in);
LinkedListNode list = new LinkedListNode();
do{
System.out.println("Enter the option you want to run");
System.out.println("1. remove duplicates\n2. Print List\n 3. Make List\n 4.kth to last element");
int option = in.nextInt();
switch(option){
case 1: // remove duplicates
System.out.println("option chosen:"+option);
list.removeDuplicates();
break;
case 2:
list.printList();
break;
case 3:
list.makeList(list,in);
break;
case 4:
System.out.println(" Enter k");
int j = list.kthLastElement(list,in.nextInt());
break;
default:
break;
}
System.out.println("Do you want to continue ?");
cont = in.nextInt();
}while(cont == 1);
in.close();
}
}
class LinkedListNode{
private int data;
private LinkedListNode next = null;
public LinkedListNode(int d){
data = d;
next = null;
}
public LinkedListNode() {
}
// appends data to the List
void appendData(int d){
LinkedListNode end = new LinkedListNode(d);
LinkedListNode n = this;
while(n.next != null){
n = n.next;
}
n.next = end;
}
// creates the LinkedList taking the input
void makeList(LinkedListNode list, Scanner in){
System.out.println("Enter the list");
int len = in.nextInt();
while(len-- > 0){
list.appendData(in.nextInt());
}
}
//implementing the recursive solution
int kthLastElement(LinkedListNode head,int k){
if(head == null){
return 0;
}
else{
int i = kthLastElement(head.next,k)+1;
if(i==k)
System.out.println(head.data);
return i;
}
}
// print the entire LinkedList O(n) time
void printList(){
LinkedListNode n = this;
while(n.next!= null){
n = n.next;
System.out.print(n.data+" -> ");
}
System.out.print("NULL\n");
}
// remove duplicates from the linkedList using Hashtable method
void removeDuplicates(){
Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
LinkedListNode current = this, prev = null;
while(current != null){
if(table.containsKey(current.data)){
prev.next = current.next;
}else{
table.put(current.data,true);
prev = current;
}
current = current.next;
}
}
}