DoublyCircularLinkedList.java 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. public class DoublyCircularLinkedList<T> {
  2. private static class Node<T> {
  3. T data;
  4. Node<T> next;
  5. Node<T> prev;
  6. Node(T data) {
  7. this.data = data;
  8. this.next = null;
  9. this.prev = null;
  10. }
  11. }
  12. private Node<T> head;
  13. private int size;
  14. public DoublyCircularLinkedList() {
  15. head = null;
  16. size = 0;
  17. }
  18. // Método para agregar un elemento al final de la lista
  19. public void add(T item) {
  20. Node<T> newNode = new Node<>(item);
  21. if (head == null) {
  22. head = newNode;
  23. head.next = head;
  24. head.prev = head;
  25. } else {
  26. Node<T> last = head.prev;
  27. last.next = newNode;
  28. newNode.prev = last;
  29. newNode.next = head;
  30. head.prev = newNode;
  31. }
  32. size++;
  33. }
  34. // Método para eliminar un elemento por su valor
  35. public boolean remove(T item) {
  36. if (head == null) {
  37. return false;
  38. }
  39. Node<T> current = head;
  40. do {
  41. if (current.data.equals(item)) {
  42. if (size == 1) {
  43. head = null;
  44. } else {
  45. Node<T> prevNode = current.prev;
  46. Node<T> nextNode = current.next;
  47. prevNode.next = nextNode;
  48. nextNode.prev = prevNode;
  49. if (current == head) {
  50. head = nextNode;
  51. }
  52. }
  53. size--;
  54. return true;
  55. }
  56. current = current.next;
  57. } while (current != head);
  58. return false;
  59. }
  60. // Método para verificar si la lista está vacía
  61. public boolean isEmpty() {
  62. return head == null;
  63. }
  64. // Método para obtener el tamaño de la lista
  65. public int size() {
  66. return size;
  67. }
  68. // Método para imprimir los elementos de la lista
  69. public void printList() {
  70. if (head == null) {
  71. System.out.println("La lista está vacía.");
  72. return;
  73. }
  74. Node<T> current = head;
  75. do {
  76. System.out.print(current.data + " ");
  77. current = current.next;
  78. } while (current != head);
  79. System.out.println();
  80. }
  81. public static void main(String[] args) {
  82. DoublyCircularLinkedList<Integer> list = new DoublyCircularLinkedList<>();
  83. list.add(1);
  84. list.add(2);
  85. list.add(3);
  86. System.out.print("Elementos en la lista: ");
  87. list.printList();
  88. System.out.println("Eliminando el elemento 2: " + list.remove(2));
  89. System.out.print("Elementos en la lista después de eliminar: ");
  90. list.printList();
  91. System.out.println("Tamaño de la lista: " + list.size());
  92. }
  93. }