【发布时间】:2021-04-29 14:34:16
【问题描述】:
这是我第一次使用程序集,我正在尝试实现一个链表。 每个节点是 2 个字 - 第一个是节点的值,第二个是列表中下一个节点的地址。对于最后一个节点,next 为零。 列表的基数是包含第一个节点地址的单词,如果列表为空,则为 0。
我正在尝试实现函数“添加项目”,其中第一个参数 ($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
【问题讨论】: