Java Day 24: More Linked Lists


A Node class is provided for you in the editor. A Node object has an integer data field, data, and a Node instance pointer, next, pointing to another node (i.e.: the next node in a list).

A removeDuplicates function is declared in your editor, which takes a pointer to the head node of a linked list as a parameter. Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list.

Note: The head+ pointer may be null, indicating that the list is empty. Be sure to reset your next pointer when performing deletions to avoid breaking the list.

  1. import java.io.*;
  2. import java.util.*;
  3. class Node{
  4. int data;
  5. Node next;
  6. Node(int d){
  7. data=d;
  8. next=null;
  9. }
  10. }
  11. class Solution
  12. {
  13. public static Node removeDuplicates(Node head) {
  14. Node curr = head;
  15. while (curr != null && curr.next != null) {
  16. while (curr.next != null && curr.data == curr.next.data) {
  17. curr.next = curr.next.next;
  18. }
  19. curr = curr.next;
  20. }
  21. return head;
  22. }
  23. public static Node insert(Node head,int data)
  24. {
  25. Node p=new Node(data);
  26. if(head==null)
  27. head=p;
  28. else if(head.next==null)
  29. head.next=p;
  30. else
  31. {
  32. Node start=head;
  33. while(start.next!=null)
  34. start=start.next;
  35. start.next=p;
  36. }
  37. return head;
  38. }
  39. public static void display(Node head)
  40. {
  41. Node start=head;
  42. while(start!=null)
  43. {
  44. System.out.print(start.data+" ");
  45. start=start.next;
  46. }
  47. }
  48. public static void main(String args[])
  49. {
  50. Scanner sc=new Scanner(System.in);
  51. Node head=null;
  52. int T=sc.nextInt();
  53. while(T-->0){
  54. int ele=sc.nextInt();
  55. head=insert(head,ele);
  56. }
  57. head=removeDuplicates(head);
  58. display(head);
  59. }
  60. }