Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 30 / 68

Stacks and queues (the basics of data structures)

This lesson covers implementing a stack and a queue in R, with the aim of understanding how to add and remove data for different purposes.

A stack takes out the item put in most recently (last in, first out); a queue takes out the item put in first (first in, first out). Picture a pile of books against a line of people waiting.

The sample code adds values to a vector with c() and then takes the last value with stack[length(stack)] (the stack) and the first with queue[1] (the queue). R has no dedicated stack or queue type, so these are expressed with vector operations.

A common early stumble is exactly that absence — you have to build the behaviour yourself out of vector operations, staying conscious of which end you take from.

In professional work, the mechanism of function calls is itself managed with a stack, so this also builds computer science fundamentals.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)