Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyLinkedList {
- private static class Node {
- private final int value;
- private Node next;
- private Node prev;
- Node(int value) {
- this.value = value;
- this.next = null;
- this.prev = null;
- }
- }
- private int length;
- private Node head;
- private Node tail;
- public void add(int value) {
- length++;
- if (head == null) { // добавляем самый первый элемент списка
- head = new Node(value);
- tail = head;
- return;
- }
- // добавляем
- tail.next = new Node(value);
- tail.next.prev = tail;
- tail = tail.next;
- }
- public void removeByIndex(int index) {
- Node tmpHead = head;
- boolean isFind = false;
- for (int i = 0; tmpHead != null; i++, tmpHead = tmpHead.next) {
- if (i == index) {
- isFind = true;
- break;
- }
- }
- if (!isFind) {
- return;
- }
- if (index == 0 && length == 1) { // удаляем элемент из списка с 1 элементом
- head = null;
- tail = null;
- } else if (index == 0) { // удаляем первый элемент с длиной списка больше 1
- head = head.next;
- } else if (index == length - 1) { // удаляем последний элемент с длиной списка больше 1
- tail = tail.prev;
- tail.next = null;
- } else { // удаляем остальные элементы с длиной списка > 2
- tmpHead.prev.next = tmpHead.next;
- }
- length--;
- }
- @Override
- public String toString() {
- String result = "[";
- Node tmpHead = head;
- while (tmpHead != null) {
- result += String.format("%d, ", tmpHead.value);
- tmpHead = tmpHead.next;
- }
- if (length > 0) {
- result = result.substring(0, result.length() - 2);
- }
- result += "]";
- return result;
- }
- public Node getHead() {
- return head;
- }
- public Node getTail() {
- return tail;
- }
- public int getLength() {
- return length;
- }
- public void printList() {
- System.out.println(this + ", length: " + getLength());
- }
- public void printPointers() {
- System.out.println("head -> " + (getHead() == null ? null : getHead().value));
- System.out.println("tail -> " + (getTail() == null ? null : getTail().value));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement