Skip to content
This repository has been archived by the owner on Oct 3, 2023. It is now read-only.

Day 5 using a Stack #3

Closed
cpswan opened this issue Dec 7, 2022 · 1 comment
Closed

Day 5 using a Stack #3

cpswan opened this issue Dec 7, 2022 · 1 comment

Comments

@cpswan
Copy link
Owner

cpswan commented Dec 7, 2022

Things really start to go amiss with this:

create a push pop stack in dart
To create a push-pop stack in Dart, you can use the Stack class from the dart:collection library. This class provides a last-in-first-out (LIFO) data structure that allows you to push elements onto the stack and pop them off the stack.

Here's an example of how to use the Stack class to create a push-pop stack:
// Import the dart:collection library
import 'dart:collection';

void main() {
  // Create a Stack
  Stack<int> stack = Stack();

  // Push some elements onto the stack
  stack.push(1);
  stack.push(2);
  stack.push(3);

  // Print the stack
  print(stack);  // Output: [1, 2, 3]

  // Pop an element off the stack
  int element = stack.pop();

  // Print the popped element and the updated stack
  print(element);  // Output: 3
  print(stack);  // Output: [1, 2]
}
In the above example, we first import the dart:collection library and create a Stack called stack. We then use the push() method to push some elements onto the stack.

Next, we use the pop() method to pop an element off the stack, and print the popped element and the updated stack.

Note that the Stack class is a generic class, which means that you need to specify the type of elements that the stack will hold when you create the stack. In this example, we create a Stack of int elements, but you can use any type that you want.

I hope this helps! Let me know if you have any other questions.

image
image

@cpswan
Copy link
Owner Author

cpswan commented Dec 7, 2022

dart:collection doesn't actually have a Stack class :0

So instead I need to create my own (using Queue from dart:collection):

class Stack<T> {
  final _stack = Queue<T>();

  int get length => _stack.length;

  bool canPop() => _stack.isNotEmpty;
  
  void clearStack(){
    while(_stack.isNotEmpty){
      _stack.removeLast();
    }
  }

  void push(T element) {
    _stack.addLast(element);
  }

  T pop() {
    T lastElement = _stack.last;
    _stack.removeLast();
    return lastElement;
  }

  T peek() => _stack.last;

}

@cpswan cpswan closed this as completed Dec 7, 2022
@cpswan cpswan changed the title Day 05 using a Stack Day 5 using a Stack Dec 13, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant