54 lines
1.1 KiB
Plaintext
54 lines
1.1 KiB
Plaintext
import ballerina/io;
|
|
|
|
class Stack {
|
|
private any[] s = [];
|
|
|
|
function push(any a) {
|
|
self.s.push(a);
|
|
}
|
|
|
|
function length() returns int {
|
|
return self.s.length();
|
|
}
|
|
|
|
function isEmpty() returns boolean {
|
|
return self.length() == 0;
|
|
}
|
|
|
|
function pop() returns any? {
|
|
if !self.isEmpty() {
|
|
return self.s.pop();
|
|
}
|
|
return ();
|
|
}
|
|
|
|
function peek() returns any? {
|
|
if !self.isEmpty() {
|
|
return self.s[self.length() - 1];
|
|
}
|
|
return ();
|
|
}
|
|
|
|
function clear() {
|
|
self.s.removeAll();
|
|
}
|
|
|
|
function toString() returns string {
|
|
return self.s.toString();
|
|
}
|
|
}
|
|
|
|
public function main() {
|
|
Stack s = new;
|
|
s.push(1);
|
|
s.push(2);
|
|
io:println("Stack contains ", s);
|
|
io:println("Number of elements in stack = ", s.length());
|
|
any item = s.pop();
|
|
io:println(item, " popped from the stack");
|
|
io:println("Last element is now ", s.peek());
|
|
s.clear();
|
|
io:println("Stack cleared");
|
|
io:println("Is stack now empty? ", s.isEmpty() ? "yes" : "no");
|
|
}
|