Advertisement
Guest User

Untitled

a guest
Feb 19th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.82 KB | None | 0 0
  1. package datastruct;
  2.  
  3.  
  4. public class DataStruct {
  5. int Listsize=0;
  6. class Node{
  7. int data;
  8. Node previous;
  9. Node next;
  10.  
  11. public Node(int data) {
  12. this.data = data;
  13. }
  14. }
  15.  
  16. //Represent the head and tail of the doubly linked list
  17. Node head, tail = null;
  18.  
  19. //addNode() will add a node to the list
  20. public void addNode(int data) {
  21. //Create a new node
  22. Node newNode = new Node(data);
  23. Listsize++;
  24.  
  25. //If list is empty
  26. if(head == null) {
  27. //Both head and tail will point to newNode
  28. head = tail = newNode;
  29. //head's previous will point to null
  30. head.previous = tail;
  31. //tail's next will point to null, as it is the last node of the list
  32. tail.next = null;
  33. }
  34. else {
  35. //newNode will be added after tail such that tail's next will point to newNode
  36. tail.next = newNode;
  37. //newNode's previous will point to tail
  38. newNode.previous = tail;
  39. //newNode will become new tail
  40. tail = newNode;
  41. //As it is last node, tail's next will point back to head
  42. tail.next = head;
  43. }
  44. }
  45.  
  46. //display() will print out the nodes of the list
  47. public void display() {
  48. int counter=0;
  49. //Node current will point to head
  50. Node current = head;
  51. if(head == null) {
  52. System.out.println("List is empty");
  53. return;
  54. }
  55. System.out.println("Nodes of doubly linked list: ");
  56. while(counter != Listsize ) {
  57. //Prints each node by incrementing the pointer.
  58.  
  59. System.out.print(current.data + " ");
  60. current = current.next;
  61. counter++;
  62. }
  63. }
  64. public void findDupes(){
  65. int counter=0;
  66. Node next;
  67. Node current = head;
  68. next = current.next;
  69. do {
  70. if (current.data == next.data){
  71. System.out.println("Found duplicate record between "+current.data+" location "+counter+" and "+next.data+" location "+(counter+1));
  72. }
  73. else
  74. next = next.next;
  75. current = next;
  76. counter++;
  77. } while (counter != Listsize);
  78.  
  79. }
  80. public static void main(String[] args) {
  81.  
  82. DataStruct dList = new DataStruct();
  83. //Add nodes to the list
  84. dList.addNode(562);
  85. dList.addNode(455);
  86. dList.addNode(655);
  87. dList.addNode(344);
  88. dList.addNode(455);
  89. //Displays the nodes present in the list
  90. dList.display();
  91. dList.findDupes();
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement