
Example of writing "pointer chasing" program in assembly language.

Goal, to test if a number is in a list.

Data structure  (singly linked list)

A list is made out of an array of nodes.  A node has two fields: the first one contains the number, the second one contains an index to the next node. The last node has 0 in the next field, signify the end of the list. For example, this is a list of number <11,22,33>.  The list start at index 100.

address: 100  101   102   103   104   105   106
data:    11   102   22    104   33    0     ...

Pseudo code

Let L be a list, x is a number.

member(x, L)
  if head(L) == x return yes
  while tail(L) != 0
    if head(L) == x return yes
    L = tail(L)
  return no

We can improve this program a bit.

member2(x, L)
  while L != 0
    if head(L) == x return yes
    L = tail(L)
  return no

It can also be written in a recursive form.

memberrec(x, L)
  if head(L) == x return yes
  if tail(L) == 0 return no
  return memberrec(x, tail(L))


We write the second version of program in s21 assembly language.
The program runs  "member2(22,L)"   where L = 100.  That is, it checks whether 22 is in the list L.

How to access head(L) and tail(L)?  We use index addressing, assume base address of L is in r2, then 

  ld r4 +r0 r2   

will load M[0+r2] to r4 which is exactly head(L).  For tail(L)
we need offset 1.  Let assume r1 is 1, then

  ld r4 +r1 r2

will load M[1+r2] to r4, tail(L).

Use r1 for c1, r2 base, r3 x, r4 value, r5 flag.

;; member of list

.code 0
:member2
  mv r1 #1            ;; constant 1
  mv r2 #100          ;; base address L
  mv r3 #44           ;; x = 22
:loop
  jf r2 no            ;;  while L != 0
  ld r4 +r0 r2        ;;  head(L)
  eq r5 r4 r3         ;;  head(L) == x ?
  jt r5 yes
  ld r2 +r1 r2        ;;  L = tail(L)
  jmp loop
:yes
  mv r5 #1
  jmp exit
:no 
  mv r5 #0
:exit
  trap 0

.data 100 
  11 102 22 104 33 0   ;; list L at 100
.end  

