From 58584c08c8c1fe7679a416bcd2ebff8c0ad1befe Mon Sep 17 00:00:00 2001 From: ritagupta09a <117037248+ritagupta09a@users.noreply.github.com> Date: Mon, 31 Oct 2022 00:07:24 +0530 Subject: [PATCH] Create cd19 --- cd19 | 83 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 cd19 diff --git a/cd19 b/cd19 new file mode 100644 index 0000000..438a660 --- /dev/null +++ b/cd19 @@ -0,0 +1,83 @@ +// Java program to remove duplicates from a sorted linked list +class LinkedList +{ + Node head; // head of list + + /* Linked list Node*/ + class Node + { + int data; + Node next; + Node(int d) {data = d; next = null; } + } + + void removeDuplicates() + { + /*Another reference to head*/ + Node curr = head; + + /* Traverse list till the last node */ + while (curr != null) { + Node temp = curr; + /*Compare current node with the next node and + keep on deleting them until it matches the current + node data */ + while(temp!=null && temp.data.equals(curr.data)) { + temp = temp.next; + } + /*Set current node next to the next different + element denoted by temp*/ + curr.next = temp; + curr = curr.next; + } + } + + /* Utility functions */ + + /* Inserts a new Node at front of the list. */ + public void push(int new_data) + { + /* 1 & 2: Allocate the Node & + Put in the data*/ + Node new_node = new Node(new_data); + + /* 3. Make next of new Node as head */ + new_node.next = head; + + /* 4. Move the head to point to new Node */ + head = new_node; + } + + /* Function to print linked list */ + void printList() + { + Node temp = head; + while (temp != null) + { + System.out.print(temp.data+" "); + temp = temp.next; + } + System.out.println(); + } + + /* Driver program to test above functions */ + public static void main(String args[]) + { + LinkedList llist = new LinkedList(); + llist.push(20); + llist.push(13); + llist.push(13); + llist.push(11); + llist.push(11); + llist.push(11); + + System.out.println("List before removal of duplicates"); + llist.printList(); + + llist.removeDuplicates(); + + System.out.println("List after removal of elements"); + llist.printList(); + } +} +/* This code is contributed by Rajat Mishra */