Determining the size of the stack


The size operation tells the caller about the current size of the stack. Unlike in the array implementation, where we have the topIndex which we use to get the size of the stack, the linked list implementation does not have a topIndex. The only way to calculate the size of a linked list on the fly is to traverse it and count the nodes, which is an O(n) operation (where n is the number of nodes) and is too expensive to do on every size() call. For this reason, we store a currentSize variable in the stack class, which keeps track of the current size of the stack.

Size of the stack is stored in a member variable of the stack class

Algorithm

Liking the course? Check our discounted plans to continue learning.