Linked Structures
Build a Singly Linked List
Construct a singly linked list by allocating one node per value and
chaining next pointers. Establishes the node + head + tail model used by
every later linked-list lesson.
Algorithm
Canonical input [10, 20, 30, 40] builds the chain
head -> 10 -> 20 -> 30 -> 40 -> null with one node appended per step.
Basic Implementation
basic.f90
program linked_list_build
implicit none
type :: list_node
integer :: value
type(list_node), pointer :: next => null()
end type list_node
integer :: values(4) = [10, 20, 30, 40]
integer :: i
type(list_node), pointer :: head, tail, node
head => null()
tail => null()
do i = 1, 4
allocate(node)
node%value = values(i)
node%next => null()
if (.not. associated(head)) then
head => node
else
tail%next => node
end if
tail => node
end do
end program linked_list_build
Complexity
- Time: O(n) with a tail pointer
- Space: O(n)
Implementation notes
- Fortran: a small
type :: list_nodewith aninteger :: valueand atype(list_node), pointer :: nextfield is the idiomatic node. The=> null()default lets the tail carry an unassociated pointer. - The replay never shows pointer addresses; nodes are labelled
node(<value>)and the chain view is rendered as1 -> 2 -> ... -> null.
node chain
Each node carries a value and a `next` pointer to the following node or `null()`.