Program in Java
1- Write a code to remove continuous repeatitive elements of a Linked List.
Example:
Given: -10 -> 3 -> 3 -> 3 -> 5 -> 6 -> 6 -> 3 -> 2 -> 2 -> NULL
The answer: -10 -> 3 -> 5 -> 6 -> 3 -> 2 -> NULL
Program to remove continuous repetitive elements of a Linked List in Java :
import java.util.*;
//Creating the class
class LinkedList
{
//Initializing the head node
Node head;
//Creating the node class
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
//Function to remove the continuous repetitive elements in the
linked list
void removeRepetitive()
{
Node current = head;
//Comparing each node with its next node whether they are same or
not
while (current != null) {
Node temp = current;
while(temp!=null && temp.data==current.data) {
temp = temp.next;
}
current.next = temp;
current = current.next;
}
}
//Function to push the elements to the linked list
public void push(int new_data)
{
Node newNode = new Node(new_data);
newNode.next = head;
head = newNode;
}
//Just a normal function to print the given linked list
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
//Main function
public static void main(String args[])
{
//Creating the linked list and taking the size and
elements of the linked list as input from the user
LinkedList linkedList = new LinkedList();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size :");
int n = sc.nextInt();
System.out.println("Enter the values :");
for(int i=0; i<n; i++) {
int t = sc.nextInt();
linkedList.push(t);
}
System.out.println("List before removal of duplicates");
linkedList.printList();
//Calling the function to remove continuos repetitive
elements
linkedList.removeRepetitive();
System.out.println("List after removal of elements");
linkedList.printList();
}
}
Program Screenshots :
Copying and pasting can result in improper code format. In that case, you can see the following screenshots for reference :
Output :
If you liked my answer, then please give me a thumbs up.
Get Answers For Free
Most questions answered within 1 hours.