Stacks (Cambridge (CIE) A Level Computer Science): Revision Note

Exam code: 9618

Robert Hampton

Written by: Robert Hampton

Reviewed by: James Woodhouse

Updated on

Implementing a stack

How do you program a stack?

  • To recap the main operations of stacks and how they work, read the ADT overview

  • When programming a stack, the main operations listed below must be included in your program.

  • The main operations for stacks are:

Main operations

Operation

Pseudocode

Python

Java

isEmpty()

FUNCTION isEmpty(s : Stack) RETURNS BOOLEAN RETURN s.top = -1 ENDFUNCTION

def isEmpty(self): return len(self.stack) == 0

stack.isEmpty();

isFull()

FUNCTION isFull(s : Stack) RETURNS BOOLEAN RETURN s.top = s.capacity - 1 ENDFUNCTION

def isFull(self): return len(self.stack) == self.capacity

public boolean isFull() { return top == capacity - 1; }

push(value)

PROCEDURE push(s : REF Stack, value : INTEGER) IF NOT isFull(s) THEN s.top ← s.top + 1 s.items[s.top] ← value ELSE OUTPUT "Stack is full" ENDIF ENDPROCEDURE

stack.push(1)

stack.push(1);

pop()

FUNCTION pop(s : REF Stack) RETURNS INTEGER IF NOT isEmpty(s) THEN DECLARE value : INTEGER value ← s.items[s.top] s.top ← s.top - 1 RETURN value ELSE RETURN -1 ENDIF ENDFUNCTION

popped_item = stack.pop()

int poppedItem = stack.pop();

peek()

FUNCTION peek(s : Stack) RETURNS INTEGER IF NOT isEmpty(s) THEN RETURN s.items[s.top] ELSE RETURN -1 ENDIF ENDFUNCTION

def peek(self): if not self.isEmpty(): return self.stack[-1] else: return None

int topItem = stack.peek();

size()

FUNCTION size(s : Stack) RETURNS INTEGER RETURN s.top + 1 ENDFUNCTION

size = len(stack)

int size = stack.size();

  • In pseudocode, we assume a record-based stack with fields like items, top, and capacity

  • Python uses built-in lists or a class with .push() and .pop() methods

  • Java uses Stack<E> from java.util.Stack

Stack in operation (Pseudocode)

TYPE Stack
    DECLARE items : ARRAY[0:4] OF INTEGER
    DECLARE top : INTEGER
    DECLARE capacity : INTEGER
ENDTYPE

// Initialise stack
DECLARE s : Stack
s.top ← -1
s.capacity ← 5

// Push 3 values onto the stack
CALL push(s, 10)
CALL push(s, 20)
CALL push(s, 30)

// Peek at the top item
OUTPUT "Top item is ", peek(s)

// Pop 2 values from the stack
DECLARE val : INTEGER
val ← pop(s)
OUTPUT "Popped value: ", val

val ← pop(s)
OUTPUT "Popped value: ", val

// Output current stack size
OUTPUT "Current size: ", size(s)
  • Defines a Stack structure with a fixed-size array of 5 items, a top pointer, and a capacity

  • Initialises the stack with top ← -1 to indicate it is empty

  • Pushes 3 values (10, 20, 30) onto the stack one by one:

    • Each push increases top and adds the value to the items array

  • Peeks at the current top of the stack:

    • Returns 30 without removing it

  • Pops two values off the stack:

    • First pop returns 30, second returns 20

    • Each pop decreases top by 1

  • Outputs the current size of the stack:

    • After popping twice, only one value (10) remains → size is 1

Python

class Stack:
    def __init__(self, capacity):
        self.stack = []
        self.capacity = capacity

    def isEmpty(self):
        return len(self.stack) == 0

    def isFull(self):
        return len(self.stack) == self.capacity

    def push(self, value):
        if not self.isFull():
            self.stack.append(value)
        else:
            print("Stack is full")

    def pop(self):
        if not self.isEmpty():
            return self.stack.pop()
        else:
            return None

    def peek(self):
        if not self.isEmpty():
            return self.stack[-1]
        else:
            return None

    def size(self):
        return len(self.stack)


# Stack in operation
s = Stack(5)

# Push 3 values
s.push(10)
s.push(20)
s.push(30)

# Peek at top
print("Top item is", s.peek())

# Pop 2 values
print("Popped value:", s.pop())
print("Popped value:", s.pop())

# Output current size
print("Current size:", s.size())

Java

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> s = new Stack<>();

        // Push 3 values
        s.push(10);
        s.push(20);
        s.push(30);

        // Peek at top
        System.out.println("Top item is " + s.peek());

        // Pop 2 values
        System.out.println("Popped value: " + s.pop());
        System.out.println("Popped value: " + s.pop());

        // Output current size
        System.out.println("Current size: " + s.size());
    }
}

Worked Example

Study the pseudocode function PushAnimal():

FUNCTION PushAnimal(DataToPush : STRING) RETURNS BOOLEAN
  IF AnimalTopPointer = 20 THEN
    RETURN FALSE
  ELSE
    Animal[AnimalTopPointer] ← DataToPush
    AnimalTopPointer ← AnimalTopPointer + 1
    RETURN TRUE
  ENDIF
ENDFUNCTION

Write program code for the function PushAnimal()[3]

Answer

  • Function header (and close where appropriate) with parameter, checking if full (AnimalTopPointer = 20) and returning false [1 mark]

  • If not full, inserting parameter value into AnimalTopPointer [1 mark]

  • …incrementing pointer and returning true [1 mark]

Example program code:

Java

public static Boolean PushAnimal(String DataToPush){
  if(AnimalTopPointer == 20){
    return false;
  }else{
    Animal[AnimalTopPointer] = DataToPush;
    AnimalTopPointer++;
    return true;
  }
}

VB.NET

Function PushAnimal(DataToPush)
  If AnimalTopPointer = 20 Then
    Return False
  Else
    Animal(AnimalTopPointer) = DataToPush
    AnimalTopPointer = AnimalTopPointer + 1
    Return True
  End If
End Function

Python

def PushAnimal(DataToPush):
  global AnimalTopPointer
  global ColourTopPointer
  if AnimalTopPointer == 20:
    return False
  else:
    Animal.append(DataToPush)
    AnimalTopPointer +=1
    return True

You've read 0 of your 5 free revision notes this week

Unlock more, it's free!

Join the 100,000+ Students that ❤️ Save My Exams

the (exam) results speak for themselves:

Did this page help you?

Robert Hampton

Author: Robert Hampton

Expertise: Computer Science Content Creator

Rob has over 16 years' experience teaching Computer Science and ICT at KS3 & GCSE levels. Rob has demonstrated strong leadership as Head of Department since 2012 and previously supported teacher development as a Specialist Leader of Education, empowering departments to excel in Computer Science. Beyond his tech expertise, Robert embraces the virtual world as an avid gamer, conquering digital battlefields when he's not coding.

James Woodhouse

Reviewer: James Woodhouse

Expertise: Computer Science & English Subject Lead

James graduated from the University of Sunderland with a degree in ICT and Computing education. He has over 14 years of experience both teaching and leading in Computer Science, specialising in teaching GCSE and A-level. James has held various leadership roles, including Head of Computer Science and coordinator positions for Key Stage 3 and Key Stage 4. James has a keen interest in networking security and technologies aimed at preventing security breaches.