Quick actions

cmd+k|ctrl+k

Navigation

Languages

Stacks

Snippet info

Language

Dart

Visibility

public

Author

obihenry578

Created

2025-02-11T08:54:00.089095Z

Updated

2025-02-12T08:21:11.479322Z

class Node{
   late dynamic value;
   late dynamic next;
    Node(value){
        this.value = value;
        this.next = null;
        
    }
}

class Stack{
   late dynamic top;
   late dynamic bottom;
   late int length;
    Stack(){
        this.top = null;
        this.bottom = null;
        this.length = 0;
    }
    
    push(value){
        Node newNode = new Node(value);
    if(length == 0){
        top = newNode;
        bottom = top;
        
    }else{
         newNode.next = top;
         top = newNode;
    }
    length++;
    
}

// remove the last push
    pop(){
        // dynamic tempTop = top; 
        top = top.next;
        
        length--;
    }
    
    // return the top;
    peek(){
        return top!= null? top.value.toString(): 'empty';
    }
    
    @override
    String toString(){
       List<dynamic> values = [];
    Node? current = top;
    while (current != null) {
      values.add(current.value);  // Add only values
      current = current.next;
    }
     return {
      'top': top?.value,
      'bottom': bottom?.value,
      'length': length,
      'elements': values
    } .toString();
  
    }
}



void main() {
    Stack stack = new Stack();
    stack.push(23);
    stack.push(25);
    stack.push(26);
    stack.push(27);
    stack.push(28);
    stack.push(29);
    stack.push(24);
    stack.pop();
    print( stack.peek());
    print(stack);
}
INFO