Showing posts with label java interview. Show all posts
Showing posts with label java interview. Show all posts

Monday, July 17, 2017

LinkedList Implementation in Java


LinkedList Implementation:
Below is the code snippet don't want to elaborate on what each of it, its self explanatory. Read it understand the constant. Its very essential to know how and what to alternate. Definite starter question to implement Linked-List in java in any core Java interview.


public class Node{

Node next;
int data;
public Node(int data) {
this.data = data;
}


public class LinkedList {
Node head;

public void append(int data) {

if (head ==null){
head = new Node(data);
return;
}

Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(data);
}

public void prepend (int data){
Node newHead = new Node(data);
newHead.next = head;
head = newHead;

}

public void deleteWithValue(int data){
if(head == null ) return;

if(head.data == data) {
head = head.next;
return;
}

while (current.next != null)
{
if (current.next.data == data){
current.next = current.next.next;
return;
}

}


}

}

public static void main(String args[]){

LinkedList list = new LinkedList();
list.append(20);
list.append(30);
System.out.println(list);
list.prepend(100);
System.out.println(list);
list.deleteWithValue(20);
System.out.println(list);

}