| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- public class DoublyLinkedList {
- private Node head; // Referencia al primer nodo
- private Node tail; // Referencia al último nodo
- // Clase interna para los nodos de la lista
- private static class Node {
- int data;
- Node next;
- Node prev;
- Node(int data) {
- this.data = data;
- this.next = null;
- this.prev = null;
- }
- }
- // Método para agregar un nodo al final de la lista
- public void addLast(int data) {
- Node newNode = new Node(data);
- if (tail == null) {
- head = newNode;
- tail = newNode;
- } else {
- tail.next = newNode;
- newNode.prev = tail;
- tail = newNode;
- }
- }
- // Método para agregar un nodo al principio de la lista
- public void addFirst(int data) {
- Node newNode = new Node(data);
- if (head == null) {
- head = newNode;
- tail = newNode;
- } else {
- newNode.next = head;
- head.prev = newNode;
- head = newNode;
- }
- }
- // Método para eliminar un nodo al final de la lista
- public void removeLast() {
- if (tail == null) {
- return;
- }
- if (head == tail) {
- head = null;
- tail = null;
- } else {
- tail = tail.prev;
- tail.next = null;
- }
- }
- // Método para eliminar un nodo al principio de la lista
- public void removeFirst() {
- if (head == null) {
- return;
- }
- if (head == tail) {
- head = null;
- tail = null;
- } else {
- head = head.next;
- head.prev = null;
- }
- }
- // Método para imprimir la lista desde el principio
- public void printList() {
- Node current = head;
- while (current != null) {
- System.out.print(current.data + " <-> ");
- current = current.next;
- }
- System.out.println("null");
- }
- public static void main(String[] args) {
- DoublyLinkedList dll = new DoublyLinkedList();
- dll.addLast(1);
- dll.addLast(2);
- dll.addLast(3);
- System.out.println("Lista después de agregar elementos:");
- dll.printList();
- dll.addFirst(0);
- System.out.println("Lista después de agregar un elemento al principio:");
- dll.printList();
- dll.removeLast();
- System.out.println("Lista después de eliminar el último elemento:");
- dll.printList();
- dll.removeFirst();
- System.out.println("Lista después de eliminar el primer elemento:");
- dll.printList();
- }
- }
|