Sunday, February 6, 2022

Remove Duplicates In A Sorted Linked List

I/O:

10 2 2 2 3 3 5 5 5 5 5


O/P:

2 2 2 3 3 5 5 5 5 5 2 3 5



import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Remove_Duplicates_In_A_Sorted_LinkedList {
public static class Node {
int data;
Node next;
}

public static class LinkedList {
Node head;
Node tail;
int size;

void addLast(int val) {
Node temp = new Node();
temp.data = val;
temp.next = null;

if (size == 0) {
head = tail = temp;
} else {
tail.next = temp;
tail = temp;
}

size++;
}

public int size() {
return size;
}

public void display() {
for (Node temp = head; temp != null; temp = temp.next) {
System.out.print(temp.data + " ");
}
System.out.println();
}

// write your code here
public void removeDuplicates() {
Node temp = head;

while (temp.next != null) {
if (temp.data == temp.next.data) {
temp.next = temp.next.next;
} else {
temp = temp.next;
}
}
}


}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int n1 = Integer.parseInt(br.readLine());
LinkedList l1 = new LinkedList();
String[] values1 = br.readLine().split(" ");
for (int i = 0; i < n1; i++) {
int d = Integer.parseInt(values1[i]);
l1.addLast(d);
}

l1.display();
l1.removeDuplicates();
l1.display();
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...