DoublyLinkedList.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. public class DoublyLinkedList {
  2. private Node head; // Referencia al primer nodo
  3. private Node tail; // Referencia al último nodo
  4. // Clase interna para los nodos de la lista
  5. private static class Node {
  6. int data;
  7. Node next;
  8. Node prev;
  9. Node(int data) {
  10. this.data = data;
  11. this.next = null;
  12. this.prev = null;
  13. }
  14. }
  15. // Método para agregar un nodo al final de la lista
  16. public void addLast(int data) {
  17. Node newNode = new Node(data);
  18. if (tail == null) {
  19. head = newNode;
  20. tail = newNode;
  21. } else {
  22. tail.next = newNode;
  23. newNode.prev = tail;
  24. tail = newNode;
  25. }
  26. }
  27. // Método para agregar un nodo al principio de la lista
  28. public void addFirst(int data) {
  29. Node newNode = new Node(data);
  30. if (head == null) {
  31. head = newNode;
  32. tail = newNode;
  33. } else {
  34. newNode.next = head;
  35. head.prev = newNode;
  36. head = newNode;
  37. }
  38. }
  39. // Método para eliminar un nodo al final de la lista
  40. public void removeLast() {
  41. if (tail == null) {
  42. return;
  43. }
  44. if (head == tail) {
  45. head = null;
  46. tail = null;
  47. } else {
  48. tail = tail.prev;
  49. tail.next = null;
  50. }
  51. }
  52. // Método para eliminar un nodo al principio de la lista
  53. public void removeFirst() {
  54. if (head == null) {
  55. return;
  56. }
  57. if (head == tail) {
  58. head = null;
  59. tail = null;
  60. } else {
  61. head = head.next;
  62. head.prev = null;
  63. }
  64. }
  65. // Método para imprimir la lista desde el principio
  66. public void printList() {
  67. Node current = head;
  68. while (current != null) {
  69. System.out.print(current.data + " <-> ");
  70. current = current.next;
  71. }
  72. System.out.println("null");
  73. }
  74. public static void main(String[] args) {
  75. DoublyLinkedList dll = new DoublyLinkedList();
  76. dll.addLast(1);
  77. dll.addLast(2);
  78. dll.addLast(3);
  79. System.out.println("Lista después de agregar elementos:");
  80. dll.printList();
  81. dll.addFirst(0);
  82. System.out.println("Lista después de agregar un elemento al principio:");
  83. dll.printList();
  84. dll.removeLast();
  85. System.out.println("Lista después de eliminar el último elemento:");
  86. dll.printList();
  87. dll.removeFirst();
  88. System.out.println("Lista después de eliminar el primer elemento:");
  89. dll.printList();
  90. }
  91. }