adding linked list source code
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
module linkedlist;
|
||||
import std::io;
|
||||
|
||||
struct Vector2 {
|
||||
int x;
|
||||
int y;
|
||||
}
|
||||
|
||||
struct Node {
|
||||
// Node.x
|
||||
//struct {
|
||||
// int x;
|
||||
//}
|
||||
Vector2 *vec;
|
||||
Node *next;
|
||||
}
|
||||
|
||||
fn Node* init(Vector2 *vec) {
|
||||
|
||||
Node *node = alloc::alloc(mem, Node);
|
||||
node.vec = vec;
|
||||
node.next = null;
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
// &self == Node *self
|
||||
fn void Node.append(&self, Vector2 *v2) {
|
||||
|
||||
Node *newNode = init(v2);
|
||||
|
||||
Node *prev;
|
||||
Node *current = self;
|
||||
while (current != null) {
|
||||
prev = current;
|
||||
current = current.next;
|
||||
}
|
||||
|
||||
prev.next = newNode;
|
||||
newNode.next = null;
|
||||
|
||||
}
|
||||
|
||||
fn void Node.insertAfter(&self, Vector2 *key, Vector2 *v2) {
|
||||
Node *newNode = init(v2);
|
||||
newNode.vec = v2;
|
||||
|
||||
Node *current = self;
|
||||
|
||||
while (current != null) {
|
||||
if (current.vec == key) {
|
||||
break;
|
||||
}
|
||||
|
||||
current = current.next;
|
||||
}
|
||||
|
||||
newNode.next = current.next;
|
||||
current.next = newNode;
|
||||
}
|
||||
|
||||
|
||||
fn void Node.deleteNode(&self, Vector2 *key) {
|
||||
Node *current = self;
|
||||
Node *prev;
|
||||
|
||||
while (current != null) {
|
||||
if (current.vec == key) {
|
||||
break;
|
||||
}
|
||||
prev = current;
|
||||
current = current.next;
|
||||
|
||||
}
|
||||
|
||||
prev.next = current.next;
|
||||
alloc::free(mem, current);
|
||||
}
|
||||
|
||||
|
||||
fn void Node.printList(&self) {
|
||||
Node *current = self;
|
||||
|
||||
io::printf("head-> ");
|
||||
while (current != null) {
|
||||
io::printf("(%d, %d) -> ", current.vec.x, current.vec.y);
|
||||
current = current.next;
|
||||
}
|
||||
|
||||
io::printfn("tail");
|
||||
}
|
||||
|
||||
fn uint Node.count(&self) {
|
||||
|
||||
uint count = 0;
|
||||
Node *current = self;
|
||||
|
||||
while (current != null) {
|
||||
count++;
|
||||
current = current.next;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
fn int main(String[] args) {
|
||||
Vector2 v1 = { .x = 1, .y = 2 };
|
||||
Vector2 v2 = { .x = 3, .y = 4 };
|
||||
Vector2 v3 = { .x = 5, .y = 6 };
|
||||
Vector2 v4 = { .x = 7, .y = 8 };
|
||||
Node* list = init(&v1);
|
||||
list.append(&v2);
|
||||
list.append(&v3);
|
||||
list.printList();
|
||||
io::printfn("count: %d", list.count());
|
||||
list.insertAfter(&v2, &v4);
|
||||
list.printList();
|
||||
io::printfn("count: %d", list.count());
|
||||
|
||||
list.deleteNode(&v4);
|
||||
list.printList();
|
||||
io::printfn("count: %d", list.count());
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user