За първи път използвам асемблиране и се опитвам да внедря свързан списък. Всеки възел е 2 думи - първата е стойността на възела, а втората е адреса на следващия възел в списъка. За последния възел next е нула. Основата на списъка е дума, съдържаща адреса на първия възел или 0, ако списъкът е празен.
Опитвам се да внедря функцията add item, където първият параметър ($a0) е адресът на основата на списъка, а $a1 е адрес, който съхранява стойността, която искам да добавя към моя списък. За да направя това, се опитвам да обходя списъка и да намеря последния елемент, така че задавам следващата му стойност да бъде новият възел, който създадох.
Чувствам, че това е много грозно (използвам и цикъл, и увеличение) и пропускам по-лесен начин за итерация в списъка, но съм малко объркан как да направя това правилно, използвайки един цикъл, тъй като искате да спрете 1 стъпка преди края на списъка Какъв е по-добрият начин да постигнете това?
Благодаря ти!!
AddItem:
# first I make the new node:
addi $sp,$sp,-8 # we make room in stack for the new item
lw $t0,0($a1) # load new item's value from its address
sw $t0,0($sp) # set new node's value
sw $zero,4($sp) # set new node's next to 0 because it's now the last item
# now I want to find where to put it:
lw $t2,0($a0) # $t2 contains the address of the first node in the list
beq $t2,$zero,AddFirstItem # in case the list is empty and we add the first item
# if the list is not empty we need to find the last item:
add $t0,$zero,$t2 # initialize $t0 to point to first node
loop:
lw $t1,4($t0) # $t1 is the address of next item
bne $t1,$zero,increase
j addItem # when we reach here, $t0 is the last item of the list
increase: # we iterate on the items in the list using both "loop" and "increase"
add $t0,$t1,$zero # $t0 which is the current item is now updates to current item's next
j loop
addItem:
sw $sp,4($t0) # set current item ($t0) next to be the node we created
j EndAddItem
AddFirstItem:
sw $sp,0($a0) # setting the base of the list to the node we created
EndAddItem:
jr $ra