Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.dataStructures;
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class CustomDoublyLinkedList<T> implements Iterable<T> {
- private class Node<T> {
- private T value;
- private Node<T> nextNode;
- private Node<T> previousNode;
- private Node(T value) {
- this.setValue(value);
- }
- private T getValue() {
- return this.value;
- }
- private void setValue(T value) {
- this.value = value;
- }
- private Node<T> getNextNode() {
- return this.nextNode;
- }
- private void setNextNode(Node<T> nextNode) {
- this.nextNode = nextNode;
- }
- private Node<T> getPreviousNode() {
- return this.previousNode;
- }
- private void setPreviousNode(Node<T> previousNode) {
- this.previousNode = previousNode;
- }
- }
- private Node<T> head;
- private Node<T> tail;
- private int size;
- public int size() {
- return size;
- }
- public void addFirst(T element) {
- if (this.size() == 0) {
- this.head = this.tail = new Node<T>(element);
- } else {
- Node<T> newHead = new Node<T>(element);
- newHead.setNextNode(this.head);
- this.head.setPreviousNode(newHead);
- this.head = newHead;
- }
- this.size++;
- }
- public void addLast(T element) {
- if (this.size() == 0) {
- this.head = this.tail = new Node<T>(element);
- } else {
- Node<T> newTail = new Node<T>(element);
- newTail.setPreviousNode(this.tail);
- this.tail.setNextNode(newTail);
- this.tail = newTail;
- }
- this.size++;
- }
- public T removeFirst() {
- if (this.size() == 0) {
- throw new IllegalStateException("Empty list");
- }
- T firstElement = this.head.getValue();
- this.head = this.head.getNextNode();
- if (this.head != null) {
- this.head.setPreviousNode(null);
- } else {
- this.tail = null;
- }
- this.size--;
- return firstElement;
- }
- public T removeLast() {
- if (this.size() == 0) {
- throw new IllegalStateException("Empty list");
- }
- T lastElement = this.tail.getValue();
- this.tail = this.tail.getPreviousNode();
- if (this.tail != null) {
- this.tail.setNextNode(null);
- } else {
- this.head = null;
- }
- this.size--;
- return lastElement;
- }
- @Override
- public Iterator<T> iterator() {
- return new Iterator<T>() {
- private int index = size() - 1;
- @Override
- public boolean hasNext() {
- return index >= 0;
- }
- Node<T> currentNode = head;
- @Override
- public T next() {
- if (hasNext()) {
- T element = currentNode.getValue();
- currentNode = currentNode.nextNode;
- index--;
- return element;
- }
- throw new NoSuchElementException();
- }
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement