Linked List Class

Medium~20 min

Implement a LinkedList class that represents a singly linked list of integers.

The LinkedList class should support the following operations:

  • LinkedList() — Initialize an empty linked list.
  • addFirst(val) — Insert the integer val at the beginning of the list.
  • addLast(val) — Insert the integer val at the end of the list.
  • removeFirst() — Remove and return the first element. Return -1 if the list is empty.
  • contains(val) — Return true if val exists in the list, false otherwise.
  • toArray() — Return an array of all elements in the list from head to tail.
  • size() — Return the number of elements in the list.

Examples

Example 1
Input: ["LinkedList","addFirst","addFirst","addLast","toArray","removeFirst","contains","size"] [[],[2],[1],[3],[],[],[2],[]]
Output: [null,null,null,null,[1,2,3],1,true,2]
Explanation: LinkedList list = new LinkedList(); list.addFirst(2); // list: [2] list.addFirst(1); // list: [1, 2] list.addLast(3); // list: [1, 2, 3] list.toArray(); // return [1, 2, 3] list.removeFirst(); // return 1, list: [2, 3] list.contains(2); // return true list.size(); // return 2

Constraints

  • -1000 <= val <= 1000
  • At most 1000 calls will be made to addFirst, addLast, removeFirst, contains, toArray, and size
  • removeFirst returns -1 when the list is empty
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run