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
/*If you any query do comment in the comment section else like the solution*/
class LinkedList
{
Node head;
class Node
{
int val;
Node link;
Node(int d) {
val = d; link = null;
}
}
void removeDuplicates()
{
Node curr = head;
while (curr != null) {
Node ptr = curr;
while(ptr!=null && ptr.val==curr.val) {
ptr = ptr.link;
}
curr.link = ptr;
curr = curr.link;
}
}
public void push(int val)
{
Node newNode = new Node(val);
newNode.link = head;
head = newNode;
}
void printList()
{
Node ptr = head;
while (ptr != null)
{
System.out.print(ptr.val+" ");
ptr = ptr.link;
}
System.out.println();
}
public static void main(String args[])
{
LinkedList llist = new LinkedList();
llist.push(10);
llist.push(3);
llist.push(3);
llist.push(3);
llist.push(5);
llist.push(6);
llist.push(6);
llist.push(3);
llist.push(2);
llist.push(2);
System.out.print("Original List: ");
llist.printList();
llist.removeDuplicates();
System.out.print("List after removal of duplicates: ");
llist.printList();
}
}
Get Answers For Free
Most questions answered within 1 hours.