Linked Lists

Linked List (C, C++, Python, Rust, Go)

C C++ Rust Python Go
Representation
    >    
struct ListNode {
    int val;
    struct ListNode *next;
};
            

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
            
    
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
            
        
type ListNode struct {
    Val int
    Next *ListNode
}
           
Access Element

v = node->val;
next = node->next;
                
same as c


                

fast = head.next.next
slow = head.next
                

var val int = node.Val
var val int = node.Next
                
Allocate New Node

new_node = (Node*) malloc(sizeof(int))
            

new_node = new Node(10)
            
    
// Type of variable in interpreted automatically
newNode := &ListNode{Val: 1}
            
Null Check

if (node->val == nullptr)
  return nullptr;
                
same as c

if head == None or head.next == None
  return False
                

if head == nil
  return false