6. Remove duplicate elements from the sorted linked list
6. Remove duplicate elements from the sorted linked list
\Problem link :- click here
package Linked_List;
public class LinkedList__6
{
static void removeDuplicates(LinkedList list)
{
//we will traverse through the linked list starting from second element.
//we will store the previous node and we check whether the current node
//is same as that of the previous node, if it is then we will remove the ciurrent
//node
Node prev, cur;
prev = list.head;
cur = prev.next;
for(cur=prev.next; cur!=null; cur=cur.next)
{
if(cur.data == prev.data)
{
Node temp = cur.next;
prev.next = temp;
}
else
prev = cur;
}
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.push(1);
list.push(2);
list.push(2);
list.push(3);
list.push(3);
list.push(4);
System.out.println("Linked list before removing dulpicates : ");
printList(list);
removeDuplicates(list);
System.out.println("Linked list after removing dulpicates : ");
printList(list);
}
static void printList(LinkedList list)
{
for(Node temp=list.head; temp!=null; temp=temp.next)
System.out.print(temp.data + "-> ");
System.out.println("null");
}
}
Time complexity :- O(n)
Space complexity :- O(1)
Comments
Post a Comment