Linked List removal of Duplicates

 package samples.test;


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

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;
}

}


List<Integer> removeDuplicates() {
List<Integer> values = new ArrayList<>();
Node temp = head, prev = head;
while (temp != null) {
if (temp.data != prev.data) {
values.add(prev.data);
prev = temp;
}
temp = temp.next;
}
if (prev != temp) {
values.add(prev.data);
prev.next = null;
}

return values;
}

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(12);
linkedList.append(13);
linkedList.append(13);
linkedList.append(13);
linkedList.append(13);
linkedList.append(14);
linkedList.append(14);
linkedList.append(15);

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

System.out.println("-----After Removal of Duplicates------");
System.out.println(linkedList.removeDuplicates());

}
}

Comments