Linked List Java Code

 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;
}
Node current = head;
while(current.next!=null){
if(current.next.data == data){
current.next = current.next.next;
return;
}
current = current.next;
}

}

public void display(){
Node current = head;
while(current!=null){
System.out.println(current.data);
current =current.next;
}
}

public static void main(String[] args) {
LinkedList linkedList =new LinkedList();
linkedList.append(12);
linkedList.append(13);
linkedList.append(14);
linkedList.append(15);

linkedList.deleteWithValue(14);
linkedList.display();

}
}

Comments