Remove duplicates from linked list recursively

In this article, we will discuss how to remove duplicates from a sorted linked list

package com.topjavatutorial; public class LinkedListDemo { private static class Node { public int data; Node next; public Node[int data] { this.data = data; next = null; } } Node head; public static void main[String[] args] { LinkedListDemo list = new LinkedListDemo[]; list.push[10]; list.push[20]; list.push[20]; list.push[30]; System.out.println["List after removing duplicates: "]; list.removeDuplicates[]; list.display[]; } public void push[int n] { Node p = new Node[n]; p.next = head; head = p; } /* * since its a sorted list, we can just compare consecutive elements to find * the duplicates */ public void removeDuplicates[] { Node current = head; while [current != null && current.next != null] { if [current.data == current.next.data] { current.next = current.next.next; } else { current = current.next; } } } public void display[] { Node tempDisplay = head; // start at the beginning of linkedList while [tempDisplay != null] { // Executes until we don't find end of // list. System.out.println[tempDisplay.data]; tempDisplay = tempDisplay.next; // move to next Node } } }

Output :

List after removing duplicates:
30
20
10

© 2018, . All rights reserved. On republishing this post, you must provide link to original post

Share this article :

  • Click to share on LinkedIn [Opens in new window]
  • Click to share on Facebook [Opens in new window]
  • Click to share on Twitter [Opens in new window]
  • More
  • Click to share on Pinterest [Opens in new window]
  • Click to share on Flipboard [Opens in new window]
  • Click to share on Tumblr [Opens in new window]
  • Click to share on Reddit [Opens in new window]
  • Click to share on Pocket [Opens in new window]

Related

Popular Articles you may like :

  • Java 8 Interview Questions
  • RESTful CRUD operations using Jersey and Hibernate
  • Frequently asked Java Programming Interview questions on Strings

Video liên quan

Chủ Đề