Data Structure and Algorithm implementations in Mojo #168
Locked
DatirDinesher
started this conversation in
General
Replies: 3 comments
-
Heap Array implementationfrom Pointer import Pointer
from IO import print_no_newline
struct HeapArray:
var data: Pointer[Int]
var size: Int
var cap: Int
fn __init__(inout self):
self.cap = 16
self.size = 0
self.data = Pointer[Int].alloc(self.cap)
fn __init__(inout self, size: Int, val: Int):
self.cap = size * 2
self.size = size
self.data = Pointer[Int].alloc(self.cap)
for i in range(self.size):
self.data.store(i, val)
fn __del__(owned self):
self.data.free()
fn dump(self):
print_no_newline("[")
for i in range(self.size):
if i > 0:
print_no_newline(", ")
print_no_newline(self.data.load(i))
print("]") |
Beta Was this translation helpful? Give feedback.
0 replies
-
Stackfrom Pointer import Pointer
from IO import print_no_newline
struct Stack[T : AnyType]:
var data: Pointer[T]
var top : Int
var size : Int
fn __init__(inout self):
self.top = -1
self.size = 16
self.data = Pointer[T].alloc(self.size)
fn __init__(inout self,stackSize: Int):
self.top = -1
self.size = stackSize
self.data = Pointer[T].alloc(self.size)
fn isFull(inout self) -> Bool:
return self.top == self.size
fn push(inout self,value : T):
if self.isFull():
print('Stack is full')
return
self.top = self.top + 1
self.data.store(self.top, value)
fn pop(inout self) -> T :
# if self.top == -1:
# print('Stack is empty')
# return None
let popval = self.data[self.top]
self.top = self.top - 1
return popval
fn __del__(owned self):
self.data.free() Usagevar s = Stack[Int]()
s.push(10)
s.push(20)
print(s.pop())
print(s.pop()) |
Beta Was this translation helpful? Give feedback.
0 replies
-
@DatirDinesher can you show a implementation of LinkedList in mojo? I am trying but unable to pass a None node to next in the implementation. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Start
Heap Array [Available by mojo ]
LinkedList implemetation in mojo
Note: please add your working code in comment
Beta Was this translation helpful? Give feedback.
All reactions