Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hacktoberfest Create dd12 #386

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions dd12
Original file line number Diff line number Diff line change
@@ -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