Design Linked List LeetCode solution in Java
1class MyLinkedList {23public class ListNode {4public int val;5public ListNode next;67public ListNode() {}89public ListNode(int val) {10this.val = val;11}1213public ListNode(int val, ListNode next) {14this.val = val;15this.next = next;16}17}1819private ListNode head;20private ListNode tail;21private int length;2223public MyLinkedList() {24length = 0;25}2627public int get(int index) {28if (index > length - 1 || index < 0) return -1;29int thisIndex = 0;30ListNode temp = head;31while (thisIndex != index) {32temp = temp.next;33thisIndex++;34}35return temp.val;36}3738public void addAtHead(int val) {39head = new ListNode(val, head);40length++;41if (length == 1) tail = head;42}4344public void addAtTail(int val) {45length++;46if (length == 1) {47ListNode onlyNode = new ListNode(val);48head = onlyNode;49tail = head;50return;51}52tail.next = new ListNode(val);53tail = tail.next;54}5556public void addAtIndex(int index, int val) {57if (index <= length) {58if (index == 0) {59addAtHead(val);60return;61}62if (index == length) {63addAtTail(val);64return;65}66length++;67ListNode temp = head;68int thisIndex = 0;69while (thisIndex != index - 1) {70temp = temp.next;71thisIndex++;72}73temp.next = new ListNode(val, temp.next);74}75}7677public void deleteAtIndex(int index) {78if (index >= length || index < 0) return;79length--;80if (index == 0) {81head = head.next;82return;83}84ListNode temp = head;85int thisIndex = 0;86while (thisIndex != index - 1) {87temp = temp.next;88thisIndex++;89}90if (index == length) {91tail = temp;92temp.next = null;93} else temp.next = temp.next.next;94}95}