linked list values

SunJet Liu
1 min readJun 14, 2021

Write a function, linkedListValues, that takes in the head of a linked list as an argument. The function should return an array containing all values of the nodes in the linked list.

test_00:

const a = new Node("a");
const b = new Node("b");
const c = new Node("c");
const d = new Node("d");
a.next = b;
b.next = c;
c.next = d;
// a -> b -> c -> dlinkedListValues(a); // -> [ 'a', 'b', 'c', 'd' ]

test_01:

const x = new Node("x");
const y = new Node("y");
x.next = y;// x -> ylinkedListValues(x); // -> [ 'x', 'y' ]

test_02:

const q = new Node("q");// qlinkedListValues(q); // -> [ 'q' ]

test_03:

linkedListValues(null); // -> [ ]

solutions

iterative

const linkedListValues = (head) => {
const values = [];
let current = head;
while (current !== null) {
values.push(current.val);
current = current.next;
}
return values;
};
  • n = number of nodes
  • Time: O(n)
  • Space: O(n)

recursive

const linkedListValues = (head) => {
const values = [];
_linkedListValues(head, values);
return values;
};
const _linkedListValues = (head, values) => {
if (head === null) return;
values.push(head.val);
_linkedListValues(head.next, values);
};
  • n = number of nodes
  • Time: O(n)
  • Space: O(n)

--

--