Skip to content

Instantly share code, notes, and snippets.

@iporsut
Created July 18, 2019 02:46
Show Gist options
  • Save iporsut/1ad7a5b411e9217388b01eb272656837 to your computer and use it in GitHub Desktop.
Save iporsut/1ad7a5b411e9217388b01eb272656837 to your computer and use it in GitHub Desktop.
Linked List in C, Go and Ruby
#include <stdlib.h>
#include <stdio.h>
typedef struct _node {
int val;
struct _node *next;
} *node;
node node_new(int val)
{
node root = (node) malloc(sizeof(struct _node));
root->val = val;
root->next = NULL;
return root;
}
node node_prepend(int val, node root)
{
node n = root;
root = node_new(val);
root->next = n;
return root;
}
void node_destroy_all(node root)
{
node t;
while (root != NULL) {
t = root;
root = root->next;
free(t);
}
}
void node_println_all(node root)
{
while (root != NULL) {
printf("%d\n", root->val);
root = root->next;
}
}
int main()
{
node root = node_new(10);
root = node_prepend(20, root);
root = node_prepend(30, root);
node_println_all(root);
node_destroy_all(root);
root = NULL;
}
package main
import "fmt"
type Node struct {
val int
next *Node
}
func New(val int) *Node {
return &Node{
val: val,
}
}
func (root *Node) Prepend(val int) (*Node) {
n := root
root = New(val)
root.next = n
return root
}
func (root *Node) Println() {
for root != nil {
fmt.Println(root.val)
root = root.next
}
}
func main() {
root := New(10)
root = root.Prepend(20)
root = root.Prepend(30)
root.Println()
}
class LinkList
attr_accessor :val, :next
def initialize(val)
@val = val
end
def prepend(val)
new_root = LinkList.new(val)
new_root.next = self
new_root
end
def println_all
root = self
while root != nil
puts root.val
root = root.next
end
end
end
root = LinkList.new(10)
root = root.prepend(20)
root = root.prepend(30)
root.println_all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment