CodesJava

Easy learning with example program codes

how to remove duplicate elements from a linked list in java?


LinkedList:

The LinkedList class extends AbstractSequentialList and implements the List and Deque interface. It uses linked list data structure to store elements. It can contain duplicate elements. It is not synchronized.

Note: It not provides the random access facility.

Example:

package com.codesjava;
 
public class LinkedList {	 
    static Node head; 
    static class Node { 
        int data;
        Node next; 
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
 
    void removeDuplicates() {
        Node ptr1 = null, ptr2 = null, duplicate = null;
        ptr1 = head; 
        while (ptr1 != null && ptr1.next != null) {
            ptr2 = ptr1;
            while (ptr2.next != null) { 
                if (ptr1.data == ptr2.next.data) { 
                	duplicate = ptr2.next;
                    ptr2.next = ptr2.next.next;
                    System.gc();
                } else {
                    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(11);
        list.head.next = new Node(17);
        list.head.next.next = new Node(11);
        list.head.next.next.next = new Node(19);
        list.head.next.next.next.next = new Node(45);
 
        System.out.println("Linked List : ");
        list.printList(head);
 
        list.removeDuplicates();
        System.out.println("");
        System.out.println("Linked List after removing duplicates : ");
        list.printList(head);
    }
}

Output

Linked List : 
11 17 11 19 45 
Linked List after removing duplicates : 
11 17 19 45


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap