Back to 课程

Computer-Science-A-level-Ocr

0% Complete
0/0 Steps
  1. 3-3-networks
    8 主题
  2. 3-2-databases
    7 主题
  3. 3-1-compression-encryption-and-hashing
    4 主题
  4. 2-5-object-oriented-languages
    7 主题
  5. 2-4-types-of-programming-language
    4 主题
  6. 2-3-software-development
    5 主题
  7. 2-2-applications-generation
    6 主题
  8. 2-1-systems-software
    8 主题
  9. 1-3-input-output-and-storage
    2 主题
  10. 1-2-types-of-processor
    3 主题
  11. 1-1-structure-and-function-of-the-processor
    1 主题
  12. structuring-your-responses
    3 主题
  13. the-exam-papers
    2 主题
  14. 8-2-algorithms-for-the-main-data-structures
    4 主题
  15. 8-1-algorithms
    10 主题
  16. 7-2-computational-methods
    11 主题
  17. 7-1-programming-techniques
    14 主题
  18. 6-5-thinking-concurrently
    2 主题
  19. 6-4-thinking-logically
    2 主题
  20. 6-3-thinking-procedurally
    3 主题
  21. 6-2-thinking-ahead
    1 主题
  22. 6-1-thinking-abstractly
    3 主题
  23. 5-2-moral-and-ethical-issues
    9 主题
  24. 5-1-computing-related-legislation
    4 主题
  25. 4-3-boolean-algebra
    5 主题
  26. 4-2-data-structures
    10 主题
  27. 4-1-data-types
    9 主题
  28. 3-4-web-technologies
    16 主题
课 Progress
0% Complete

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()

def isEmpty(self):

return len(self.stack) == 0

// Check if the stack is empty

System.out.println(stack.isEmpty());

// Output: true

push(value)

# Push some items into the stack

stack.push(1)

// Push some items into the stack

stack.push(1);

peek()

def peek(self):

if not self.isEmpty():

return self.stack[-1]

else:

return None

// Peek the top item in the stack

int topItem = stack.peek();

System.out.println("Top item: " + topItem);

// Output: Top item: 3

pop()

# Pop items from the stack

popped_item1 = stack.pop()

 // Pop items from the stack

 int poppedItem1 = stack.pop();

size()

# Get the size of the stack

size = len(stack)

print("Size of the stack:", size) 

# Output: Size of the stack: 3

// Get the size of the stack

int size = stack.size();

System.out.println("Size of the stack: " + size);

// Output: Size of the stack: 3

isFull()

def isFull(self):

return len(self.stack) == self.capacity

public boolean isFull() {

return (top == capacity - 1);

}

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

您的邮箱地址不会被公开。 必填项已用 * 标注