Java

Помогите, пожалуйста! Это все в java

С помощью односвязного списка напишите реализацию LinkedList.
У пользователя должны быть доступны методы добавления элемента, получения элемента и удаления элемента из списк.
Условия:
- Нельзя использовать шаблоны(готовый LinkedList, методы для работы с ним)
†rômán †
†rômán †
95
Это готовый пример:

 class Node { 
T value;
Node next;

public Node(T value) {
this.value = value;
this.next = null;
}
}

public class LinkedList {
private Node head;
private Node tail;

public LinkedList() {
this.head = null;
this.tail = null;
}

// Добавление элемента в конец списка
public void add(T value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}

// Получение элемента по индексу
public T get(int index) {
if (index < 0 || index >= size()) {
return null;
}
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.value;
}

// Удаление элемента по индексу
public void remove(int index) {
if (index < 0 || index >= size()) {
return;
}
if (index == 0) {
head = head.next;
if (head == null) {
tail = null;
}
} else {
Node current = head;
Node prev = null;
for (int i = 0; i < index; i++) {
prev = current;
current = current.next;
}
prev.next = current.next;
if (current == tail) {
tail = prev;
}
}
}

// Получение размера списка
public int size() {
int count = 0;
Node current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}

public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);

System.out.println(linkedList.get(0)); // 1
System.out.println(linkedList.get(1)); // 2
System.out.println(linkedList.get(2)); // 3

linkedList.remove(1);

System.out.println(linkedList.get(1)); // 3
System.out.println(linkedList.size()); // 2
}
}
ВА
Виктор Амирасланов
69 350
Лучший ответ
Программируй на TS
Дима Любич
Дима Любич
290