Computer-Science-A-level-Ocr
-
3-3-networks8 主题
-
3-2-databases7 主题
-
3-1-compression-encryption-and-hashing4 主题
-
2-5-object-oriented-languages7 主题
-
2-4-types-of-programming-language4 主题
-
2-3-software-development5 主题
-
2-2-applications-generation6 主题
-
2-1-systems-software8 主题
-
1-3-input-output-and-storage2 主题
-
1-2-types-of-processor3 主题
-
1-1-structure-and-function-of-the-processor1 主题
-
structuring-your-responses3 主题
-
the-exam-papers2 主题
-
8-2-algorithms-for-the-main-data-structures4 主题
-
8-1-algorithms10 主题
-
7-2-computational-methods11 主题
-
7-1-programming-techniques14 主题
-
capturing-selecting-managing-and-exchanging-data
-
entity-relationship-diagrams
-
data-normalisation
-
relational-databases
-
hashing
-
symmetric-vs-asymmetric-encryption
-
run-length-encoding-and-dictionary-coding
-
lossy-and-lossless-compression
-
polymorphism-oop
-
encapsulation-oop
-
inheritance-oop
-
attributes-oop
-
methods-oop
-
objects-oop
-
capturing-selecting-managing-and-exchanging-data
-
6-5-thinking-concurrently2 主题
-
6-4-thinking-logically2 主题
-
6-3-thinking-procedurally3 主题
-
6-2-thinking-ahead1 主题
-
6-1-thinking-abstractly3 主题
-
5-2-moral-and-ethical-issues9 主题
-
5-1-computing-related-legislation4 主题
-
4-3-boolean-algebra5 主题
-
4-2-data-structures10 主题
-
4-1-data-types9 主题
-
3-4-web-technologies16 主题
-
environmental-effects
-
automated-decision-making
-
computers-in-the-workforce
-
layout-colour-paradigms-and-character-sets
-
piracy-and-offensive-communications
-
analysing-personal-information
-
monitoring-behaviour
-
censorship-and-the-internet
-
artificial-intelligence
-
the-regulation-of-investigatory-powers-act-2000
-
the-copyright-design-and-patents-act-1988
-
the-computer-misuse-act-1990
-
the-data-protection-act-1998
-
adder-circuits
-
flip-flop-circuits
-
simplifying-boolean-algebra
-
environmental-effects
stacks
Implementing a Stack
How Do You Program a Stack?
-
To recap the main operations of Stacks and how they work, follow this link
-
When programming a stack, the main operations listed below must be included in your program.
-
The main operations for Stacks are:
Main Operations
|
Operation |
Python |
Java |
|---|---|---|
|
isEmpty() |
|
|
|
push(value) |
|
|
|
peek() |
|
|
|
pop() |
|
|
|
size() |
|
|
|
isFull() |
|
|
Programming a Stack in Python
Explanation of the Python Code
-
Class Stack: Defines a Python class, Stack, with a specified capacity and an empty list to store elements.
-
Push Method: Appends an item to the stack if the stack is not full; otherwise, it prints a message to say that it is not possible.
-
Pop Method: Removes and returns the top item from the stack if it’s not empty; otherwise, it prints a message to say nothing can be popped as it is empty.
-
Peek Method: Returns the top item of the stack without removing it if the stack is not empty; otherwise, it will print a message to say the stack is empty.
-
Additional Operations: The code at the bottom includes methods to retrieve the stack size (size), check if the stack is empty (isEmpty), and check if the stack is full (isFull).
class Stack:
def __init__(self, capacity):
self.capacity = capacity
self.stack = []
def push(self, item):
if len(self.stack) < self.capacity:
self.stack.append(item)
print("Pushed item:", item)
else:
print("Stack is full. Cannot push item:", item)
def pop(self):
if not self.isEmpty():
return self.stack.pop()
else:
print("Stack is empty. Cannot pop item.")
def peek(self):
if not self.isEmpty():
return self.stack[-1]
else:
print("Stack is empty. Cannot peek.")
def size(self):
return len(self.stack)
def isEmpty(self):
return len(self.stack) == 0
def isFull(self):
return len(self.stack) == self.capacity
-
This code below is used to demonstrate the usage of the operations above with a stack of animals, pushing, popping, peeking, and checking the stack’s status.
# Create a stack with a capacity of 5
stack = Stack(5)
# Push animals onto the stack
stack.push("Dog")
stack.push("Cat")
stack.push("Elephant")
stack.push("Lion")
stack.push("Tiger")
# Try pushing more animals than the capacity allows
stack.push("Giraffe") # Output: Stack is full. Cannot push item: Giraffe
# Pop an animal from the stack
popped_animal = stack.pop()
print("Popped animal:", popped_animal) # Output: Popped animal: Tiger
# Peek at the top animal of the stack
top_animal = stack.peek()
print("Top animal:", top_animal) # Output: Top animal: Lion
# Get the size of the stack
stack_size = stack.size()
print("Stack size:", stack_size) # Output: Stack size: 4
# Check if the stack is empty
is_empty = stack.isEmpty()
print("Is stack empty?", is_empty) # Output: Is stack empty? False
# Check if the stack is full
is_full = stack.isFull()
print("Is stack full?", is_full) # Output: Is stack full? False
Programming a Stack in Java
Explanation of the Java Code
-
AnimalStack Class: Defines a class named AnimalStack that uses the Stack class to implement a stack for storing animal names with a specified capacity.
-
Push Method: Adds an animal to the stack if it’s not full; otherwise, it prints a message to say that it is not possible.
-
Pop Method: Removes and returns the top animal from the stack if it’s not empty; otherwise, it prints a message to say that it is not possible and returns null.
-
Peek Method: Returns the top animal without removing it if the stack is not empty; otherwise, it prints a message to say that it is not possible and returns null.
-
Main Method Usage: Demonstrates the usage of the AnimalStack class with a stack of animals, showcasing pushing, popping, peeking, and checking stack size and status.
import java.util.Stack;
public class AnimalStack {
private int capacity;
private Stack<String> stack;
public AnimalStack(int capacity) {
this.capacity = capacity;
this.stack = new Stack<>();
}
public void push(String animal) {
if (stack.size() < capacity) {
stack.push(animal);
System.out.println("Pushed item: " + animal);
} else {
System.out.println("Stack is full. Cannot push item: " + animal);
}
}
public String pop() {
if (!isEmpty()) {
return stack.pop();
} else {
System.out.println("Stack is empty. Cannot pop item.");
return null;
}
}
public String peek() {
if (!isEmpty()) {
return stack.peek();
} else {
System.out.println("Stack is empty. Cannot peek.");
return null;
}
}
public int size() {
return stack.size();
}
public boolean isEmpty() {
return stack.isEmpty();
}
public boolean isFull() {
return stack.size() == capacity;
}
public static void main(String[] args) {
AnimalStack stack = new AnimalStack(5);
stack.push("Dog");
stack.push("Cat");
stack.push("Elephant");
stack.push("Lion");
stack.push("Tiger");
stack.push("Giraffe"); // Output: Stack is full. Cannot push item: Giraffe
String poppedAnimal = stack.pop();
System.out.println("Popped animal: " + poppedAnimal); // Output: Popped animal: Tiger
String topAnimal = stack.peek();
System.out.println("Top animal: " + topAnimal); // Output: Top animal: Lion
int stackSize = stack.size();
System.out.println("Stack size: " + stackSize); // Output: Stack size: 4
boolean isEmpty = stack.isEmpty();
System.out.println("Is stack empty? " + isEmpty); // Output: Is stack empty? false
boolean isFull = stack.isFull();
System.out.println("Is stack full? " + isFull); // Output: Is stack full? false
}
}
Responses