MIPS汇编实现链表元素添加:遍历逻辑优化问询
AddItem in MIPS Assembly Nice job getting the basic linked list add functionality working—traversal logic is often where we can clean up code for readability and conciseness. Let’s simplify your two-label loop into a single, streamlined loop that achieves the same goal without extra branches.
Key Idea
Instead of splitting the traversal into a loop check and an increase label to update the pointer, we can combine both steps into one loop. The core adjustment is checking if the current node's next field is not null before updating our pointer—this lets us stay within a single loop structure until we hit the last node.
Optimized AddItem Implementation
AddItem: # Create new node (unchanged from your original code) addi $sp,$sp,-8 # Allocate 2 words on stack for new node lw $t0,0($a1) # Load value from input address sw $t0,0($sp) # Set new node's value field sw $zero,4($sp) # Set new node's next to 0 (it'll be the last node) # Find insertion position lw $t2,0($a0) # Load head pointer of the list beq $t2,$zero,AddFirstItem # If list is empty, jump to add first node # Single-loop traversal to find the last node add $t0,$zero,$t2 # Initialize current node pointer to head loop: lw $t1,4($t0) # Get current node's next address beq $t1,$zero,addItem # If next is 0, we found the last node—jump to add add $t0,$t1,$zero # Otherwise, move pointer to next node j loop # Repeat loop addItem: sw $sp,4($t0) # Update last node's next to point to new node j EndAddItem AddFirstItem: sw $sp,0($a0) # Set list head to new node (empty list case) EndAddItem: jr $ra # Return to caller
What Changed?
- Removed the
increaselabel: We now handle updating the current node pointer directly inside the loop, right after confirming the current node isn't the last one. - Simplified branching: The loop only breaks when we find a node with a
nextvalue of 0—this keeps all traversal logic contained within theloopblock. - Preserved original functionality: The core logic (create node, check for empty list, find last node, link new node) remains identical; we just streamlined the control flow.
This approach makes the code more readable, reduces the number of jump instructions, and keeps all traversal-related logic in one place—making it easier to debug or modify later.
内容的提问来源于stack exchange,提问作者ronihm

