From 906d817a466358ae4489b2bc150eeddce7d86ded Mon Sep 17 00:00:00 2001 From: deekshagupta11m <117037826+deekshagupta11m@users.noreply.github.com> Date: Mon, 31 Oct 2022 00:17:06 +0530 Subject: [PATCH] Create dd12 --- dd12 | 107 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 dd12 diff --git a/dd12 b/dd12 new file mode 100644 index 0000000..a3c68d7 --- /dev/null +++ b/dd12 @@ -0,0 +1,107 @@ +// Java Program to remove duplicates +// from a sorted linked list +class GFG +{ +/* Link list node */ +static class Node +{ + int data; + Node next; +}; + +// The function removes duplicates +// from a sorted list +static Node removeDuplicates(Node head) +{ + /* Pointer to store the pointer + of a node to be deleted*/ + Node to_free; + + /* do nothing if the list is empty */ + if (head == null) + return null; + + /* Traverse the list till last node */ + if (head.next != null) + { + + /* Compare head node with next node */ + if (head.data == head.next.data) + { + /* The sequence of steps is important. + to_free pointer stores the next of head + pointer which is to be deleted.*/ + to_free = head.next; + head.next = head.next.next; + removeDuplicates(head); + } + + /* This is tricky: only advance if no deletion */ + else + { + removeDuplicates(head.next); + } + } + return head; +} + +/* UTILITY FUNCTIONS */ +/* Function to insert a node at the beginning +of the linked list */ +static Node push(Node head_ref, + int new_data) +{ + /* allocate node */ + Node new_node = new Node(); + + /* put in the data */ + new_node.data = new_data; + + /* link the old list off the new node */ + new_node.next = (head_ref); + + /* move the head to point to the new node */ + (head_ref) = new_node; + return head_ref; +} + +/* Function to print nodes in a given linked list */ +static void printList(Node node) +{ + while (node != null) + { + System.out.print(" " + node.data); + node = node.next; + } +} + +/* Driver code*/ +public static void main(String args[]) +{ + /* Start with the empty list */ + Node head = null; + + /* Let us create a sorted linked list + to test the functions + Created linked list will be 11.11.11.13.13.20 */ + head = push(head, 20); + head = push(head, 13); + head = push(head, 13); + head = push(head, 11); + head = push(head, 11); + head = push(head, 11); + + System.out.println("Linked list before" + + " duplicate removal "); + printList(head); + + /* Remove duplicates from linked list */ + head = removeDuplicates(head); + + System.out.println("\nLinked list after" + + " duplicate removal "); + printList(head); +} +} + +// This code is contributed by Arnab Kundu