Design Linked List
expert · 1165 · lc medium +32 · 29.9% accepted · 3,049 likes · top 7%
Description
Implement a linked list from scratch. You may use a singly or doubly linked list. Nodes are 0-indexed.
Implement the MyLinkedList class:
- MyLinkedList() Creates an empty linked list.
- int get(int index) Returns the value at position index, or -1 if the index is out of bounds.
- void addAtHead(int val) Inserts a node with value val at the front of the list.
- void addAtTail(int val) Appends a node with value val to the end of the list.
- void addAtIndex(int index, int val) Inserts a node with value val before the node at position index. If index equals the list length, appends to the end. If index exceeds the length, does nothing.
- void deleteAtIndex(int index) Removes the node at position index if the index is valid.
Example 1:
Example 2:
Code