You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:双向链表代码陷入无限循环,输出34而非77求排查

Troubleshooting Your Doubly Linked List Infinite Loop & Unexpected Output

Hey there! Let’s work through your doubly linked list problem—infinitely looping and getting 34 instead of the expected 77. Since you’ve already checked your code a few times, let’s focus on the easy-to-miss pointer and logic slips that usually cause these issues:

Common Culprits to Check

1. Print Function Traversal Logic

The most likely culprit for an infinite loop here is broken traversal logic:

  • Wrong termination condition: If your print loop uses something like while(current != head) instead of while(current != NULL) (or your language’s equivalent of a null reference), you’ll loop forever once you circle back to the head.
  • Stuck pointer: If you forget to update the traversal pointer (e.g., missing current = current->next inside the loop), you’ll keep printing the same 34 node over and over.
  • Unset tail pointer: If your tail node’s next doesn’t point to NULL but instead points to a previous node (creating a small loop), the traversal will never end.

Doubly linked lists rely on both prev and next pointers being correctly updated—a single missing update can create a loop or wrong data flow:

  • When inserting the node with value 77, did you:
    • Update the previous node’s next to point to the new node?
    • Set the new node’s prev to point to the previous node?
    • If there was a node after the insertion point, update that node’s prev to point to the new node?
  • Accidental self-referential pointers: If a node’s next points to itself (or prev points to itself), your traversal will loop indefinitely on that single node.

3. Data Assignment Mistake

That persistent 34 output might not be a loop issue at all:

  • Did you accidentally assign the value 34 to the node that should hold 77? Double-check the line where you set the new node’s data value.
  • Are you reusing an existing node (with value 34) instead of creating a new one for 77?

Quick Debugging Steps

  • Test the print function in isolation: Create a tiny doubly linked list (e.g., nodes with values 10, 20, 30) and run your print function. If it loops or prints incorrectly, the problem is definitely in the print logic.
  • Log pointer values: Add temporary print statements to log each node’s prev and next (either their memory addresses or the data of the node they point to). This will let you spot if a pointer is creating a loop or pointing to the wrong node.
  • Validate insertion step-by-step: Walk through the code that adds the 77 node line by line. Confirm every pointer is updated correctly before moving on.

内容的提问来源于stack exchange,提问作者sambhav jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:39:41