Advertisement
Guest User

Untitled

a guest
Apr 5th, 2023
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.38 KB | None | 0 0
  1. public class MyLinkedList {
  2.   private static class Node {
  3.     private final int value;
  4.     private Node next;
  5.     private Node prev;
  6.  
  7.     Node(int value) {
  8.       this.value = value;
  9.       this.next = null;
  10.       this.prev = null;
  11.     }
  12.   }
  13.  
  14.   private int length;
  15.   private Node head;
  16.   private Node tail;
  17.  
  18.   public void add(int value) {
  19.     length++;
  20.  
  21.     if (head == null) { // добавляем самый первый элемент списка
  22.       head = new Node(value);
  23.       tail = head;
  24.       return;
  25.     }
  26.  
  27.     // добавляем
  28.     tail.next = new Node(value);
  29.     tail.next.prev = tail;
  30.     tail = tail.next;
  31.   }
  32.  
  33.   public void removeByIndex(int index) {
  34.     Node tmpHead = head;
  35.     boolean isFind = false;
  36.     for (int i = 0; tmpHead != null; i++, tmpHead = tmpHead.next) {
  37.       if (i == index) {
  38.         isFind = true;
  39.         break;
  40.       }
  41.     }
  42.  
  43.     if (!isFind) {
  44.       return;
  45.     }
  46.  
  47.     if (index == 0 && length == 1) {  // удаляем элемент из списка с 1 элементом
  48.       head = null;
  49.       tail = null;
  50.     } else if (index == 0) { // удаляем первый элемент с длиной списка больше 1
  51.       head = head.next;
  52.     } else if (index == length - 1) { // удаляем последний элемент с длиной списка больше 1
  53.       tail = tail.prev;
  54.       tail.next = null;
  55.     } else { // удаляем остальные элементы с длиной списка > 2
  56.       tmpHead.prev.next = tmpHead.next;
  57.     }
  58.  
  59.     length--;
  60.   }
  61.  
  62.   @Override
  63.   public String toString() {
  64.     String result = "[";
  65.  
  66.     Node tmpHead = head;
  67.     while (tmpHead != null) {
  68.       result += String.format("%d, ", tmpHead.value);
  69.       tmpHead = tmpHead.next;
  70.     }
  71.  
  72.     if (length > 0) {
  73.       result = result.substring(0, result.length() - 2);
  74.     }
  75.     result += "]";
  76.  
  77.     return result;
  78.   }
  79.  
  80.   public Node getHead() {
  81.     return head;
  82.   }
  83.  
  84.   public Node getTail() {
  85.     return tail;
  86.   }
  87.  
  88.   public int getLength() {
  89.     return length;
  90.   }
  91.  
  92.   public void printList() {
  93.     System.out.println(this + ", length: " + getLength());
  94.   }
  95.  
  96.   public void printPointers() {
  97.     System.out.println("head -> " + (getHead() == null ? null : getHead().value));
  98.     System.out.println("tail -> " + (getTail() == null ? null : getTail().value));
  99.   }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement