remove duplicates from singly linked list
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Function to remove duplicates from an
unsorted linked list */
void remove_duplicates() {
Node ptr1 = null, ptr2 = null, dup = null;
ptr1 = head;
/* Pick elements one by one */
while (ptr1 != null && ptr1.next != null) {
ptr2 = ptr1;
/* Compare the picked element with rest
of the elements */
while (ptr2.next != null) {
/* If duplicate then delete it */
if (ptr1.data == ptr2.next.data) {
/* sequence of steps is important here */
dup = ptr2.next;
ptr2.next = ptr2.next.next;
System.gc();
} else /* This is tricky */ {
ptr2 = ptr2.next;
}
}
ptr1 = ptr1.next;
}
}
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(10);
list.head.next = new Node(12);
list.head.next.next = new Node(11);
list.head.next.next.next = new Node(11);
list.head.next.next.next.next = new Node(12);
list.head.next.next.next.next.next = new Node(11);
list.head.next.next.next.next.next.next = new Node(10);
System.out.println("Linked List before removing duplicates : \n ");
list.printList(head);
list.remove_duplicates();
System.out.println("");
System.out.println("Linked List after removing duplicates : \n ");
list.printList(head);
}
}
Also in Java:
- primitive data types in java
- string isEmpty java
- how to make a new arraylist java
- append to arraylist by index java
- java.sql.SQLException: Before start of result set
- how to declare a linked list in java
- fibonacci series i logn java
- set html text android java
- continue in java
- How can I put a parameter into a localized string in Android?
- java copy list
- jtable disable row selection
- finding min and max from given number in java
- capcitor FERR_CLEARTEXT_NOT_PERMITTED
- java observable to observer stack overflow
- android get distance between two locations kotlin
- check if object is empty java 8
- using class in java
- replaceall in java
- Java use Base64
- Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
- java infinitew recursion
- remove duplicates from singly linked list
- Character.getNumericValue['z']