Jump to content

Singly-linked list/Traversal: Difference between revisions

Line 7:
{{Template:See also lists}}
<br><br>
 
=={{header|6502 Assembly}}==
===Using self-modifying code===
In this example, we'll create three nodes, and read the value of the last node. You can copy and paste this code into easy6502 and run it there. Note that the debugger shows that the value in the accumulator is $25, just as expected.
 
Self-modifying code is an efficient way to perform this task. Unfortunately, easy6502 does not support <code>ORG</code> directives or compile-time pointer arithmetic, so the easiest way to do this was to place a jump to the main program at the beginning and put the self-modifying section between the jump and the main program. (Easy6502's memory layout starts execution at $0600 so it was a simple matter of knowing that <code>JMP</code> takes three bytes and <code>LDA</code> takes two.)
 
The program will look up the pointer to the next node, modify the operand of the traverse function with that address, and repeat until a null pointer ($00) is read. Then it uses the same traverse function to fetch the value.
 
<lang 6502asm>define nullptr 0
jmp main
traverse:
;change the $00 to anything you want
;by writing the desired value to $0604
LDA $00,X
rts
 
main:
;create three nodes
; node 0 = #$23 stored at $0003
; node 1 = #$24 stored at $0013
; node 2 = #$25 stored at $0033
 
LDA #$03
STA $0604
;alter our code to have the starting address.
;create the linked list.
LDA #$23
STA $03
LDA #$13
STA $04
 
LDA #$24
STA $13
LDA #$33
STA $14
 
LDA #$25
STA $33
LDA #nullptr
STA $34
 
;traverse to last element and load it into A.
LDX #1
loop_traverse:
jsr traverse
;CMP #nullptr ;LDA implicitly compares to zero.
BEQ done ;if equal to nullptr, exit.
STA $0604
jmp loop_traverse
done:
dex
jsr traverse ;get the value of the last element.
brk</lang>
 
===Without self-modifying code===
This is mostly the same, except it uses the <code>($nn),y</code> addressing mode which is a bit slower, but can be executed on ROM cartridges no problem.
<lang 6502asm>define nullptr 0
define tempptr $fc
 
 
main:
;create three nodes
; node 0 = #$23 stored at $0003
; node 1 = #$24 stored at $0013
; node 2 = #$25 stored at $0033
 
;create the linked list.
LDA #$03
STA $FC ;store the pointer to node 0.
 
LDA #$23
STA $03
LDA #$13
STA $04
 
LDA #$24
STA $13
LDA #$33
STA $14
 
LDA #$25
STA $33
LDA #nullptr
STA $34
 
LDY #1
loop:
jsr traverse
BEQ done
STA $FC
BNE loop ;branch always
done:
DEY
JSR traverse
brk
 
traverse:
LDA ($FC),Y
rts</lang>
 
=={{header|AArch64 Assembly}}==
1,489

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.