Skip to main content

Structures

Definition

struct Point:
int x
int y

Instantiation

Point p
p.x = 10
p.y = 20

Nested Structures

struct Line:
Point start
Point end

Line line
line.start.x = 0
line.start.y = 0
line.end.x = 100
line.end.y = 100

Methods

struct Point:
int x
int y

public def add(self, other: Point) -> Point:
Point result
result.x = self.x + other.x
result.y = self.y + other.y
return result

Self-Referential

struct ListNode:
int value
ListNode* next

Linked List Example

struct ListNode:
int value
ListNode* next

public def create_list(n: int) -> ListNode*:
ListNode* head = 0
ListNode* current = 0
int i = 0

while i < n:
ListNode* node = new ListNode
node.value = i * 10
node.next = 0

if head == 0:
head = node
else:
current.next = node

current = node
i += 1

return head

public def sum_list(head: ListNode*) -> int:
int total = 0
ListNode* current = head

while current != 0:
total += current.value
current = current.next

return total