Problem overview
A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO (last in, first out). The lesson asks for a class MyStack that stores whole numbers in a private vector<int> data and offers four operations:
void push(int value)puts a value on top and returns nothing.int pop()removes the top value and returns it.int peek()returns the top value and leaves it on the stack.int size()returns how many values the stack holds.
The code at the bottom of the starter pushes 10, 20 and 30, then inspects and pops. After the three pushes the top is 30 and the size is 3. The first pop returns 30 and leaves size 2. Two more pops return 20 and then 10, so the values come back in the reverse of the order they went in. The stack is now empty, and it keeps working: pushing 7 gives a top of 7 and a size of 1. The output:
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
Popping or peeking at an empty stack is not part of the exercise, and the lesson's tests never do it.
Approach: the end of the vector is the top
A vector is a resizable array, and it is fast to add and remove at its end. If the end of the vector is the top of the stack, each operation maps to one vector operation:
| Stack operation | Vector call |
|---|---|
| push | push_back(value) |
| peek | back() |
| pop | back(), then pop_back() |
| size | size() |
Using the front of the vector as the top would also work, but every push and pop would have to shift all the other elements. The end needs no shifting.
pop needs a little care. In C++, pop_back() removes the last element and returns nothing, and once the element is gone you can't read it. So pop must save the value first, remove it, and then return the saved copy.
Step by step
- Declare
MyStackand write its closing};immediately, because a class ends with a semicolon. - Add the private field. Under
private:, declarevector<int> data;. Only the class's own methods can touch it, so outside code can't reorder or edit the stored values. - Open a
public:section for the methods the driver calls. - Start
pushas avoidmethod taking anintnamedvalue. - Append the value with
data.push_back(value). The newest value is now last, which makes it the top. - Start
popas a method returningint. Its body has three lines. - Save the top in an
intnamedtop, usingdata.back(). - Remove the last element with
data.pop_back(). This is why the value was saved first. - Return
top, the value the caller asked for. - Start
peekas a method returningint. - Return
data.back(). It only reads the last element, so the stack is unchanged and the size stays the same. - Start
sizeas a method returningint. - Return
data.size(): one vector element per stored value, so the vector's size is the stack's size.
The solution in C++
class MyStack {
private:
vector<int> data;
public:
void push(int value) {
data.push_back(value);
}
int pop() {
int top = data.back();
data.pop_back();
return top;
}
int peek() {
return data.back();
}
int size() {
return data.size();
}
};
class Solution {
public:
void mainFunction() {
MyStack s;
s.push(10);
s.push(20);
s.push(30);
cout << "Top: " << s.peek() << endl;
cout << "Size: " << s.size() << endl;
cout << "Pop: " << s.pop() << endl;
cout << "Size: " << s.size() << endl;
cout << "Pop: " << s.pop() << endl;
cout << "Pop: " << s.pop() << endl;
cout << "Empty size: " << s.size() << endl;
s.push(7);
cout << "Top: " << s.peek() << endl;
cout << "Size: " << s.size() << endl;
}
};
C++ details worth knowing
back()versuspop_back().back()gives access to the last element and removes nothing;pop_back()removes it and gives nothing back. Combining them is howpopreturns the value and removes it.size()converts an unsigned value.data.size()has an unsigned type,size_t, and the method returnsint, so the value is converted. For the small stacks in this lesson that is harmless. Be careful with expressions such asdata.size() - 1on an empty vector: unsigned arithmetic wraps around. For an emptyvector<int>that expression gives 18446744073709551615, not -1.- Empty stacks are undefined behaviour. Calling
back()orpop_back()on an empty vector doesn't throw an error; the behaviour is undefined. That is why the statement promises the tests never do it. A stack you ship would checksize() == 0first. - Private data.
datais hidden, so the class is free to change how it stores values without breaking the code that uses it.
Complexity
All four operations take constant time on average. push_back is amortised O(1): usually it writes into spare capacity, and occasionally the vector grows and copies its elements, which averages out. back(), pop_back() and size() are O(1). The stack uses O(n) space for the n values it holds.
Edge cases and common mistakes
- Returning without saving. Calling
pop_back()and then trying to returndata.back()returns the wrong element, the new top, not the removed one. Save the value first. - Making
peekremove the value.peekmust only read, or the size changes and later pops return the wrong numbers. - Treating the front as the top. The order of results would be wrong, or each operation would be slower.
- Reusing the stack after it empties. Nothing special is needed: pushing onto an empty stack works, as the driver's last lines show.
Testing
Push 1, 2, 3 and 4 into a new stack. Calling peek() twice gives 4 both times and the size is still 4. Popping until the size is 0 returns the values in the reverse order:
4 3 2 1
Key takeaways
- A stack is last in, first out, and the end of a vector is a natural top.
pop_back()returns nothing, so saveback()before removing it.- Keep the vector private and expose only the four operations.
