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

基于C语言链表的汉诺塔游戏实现:代码调试及遗漏点排查请求

Hey there! Let's dig into your Tower of Hanoi project—using linked lists to represent disks on pegs is such a solid way to practice data structures, great call! Since you mentioned your current code only handles disk creation (and it's a rough draft), let's go over common bugs in that part first, then cover key features you might have overlooked for the full game.

Common Bugs in Disk Creation Code

Since you haven't shared your exact code, here are the most frequent pitfalls in this stage:

  • Uninitialized next pointers: If you create a disk node but forget to set its next field to NULL, you'll end up with wild pointers when traversing or modifying the linked list later. This usually leads to crashes or weird undefined behavior. Example of the mistake:
    struct Disk* create_disk(int size) {
        struct Disk* disk = malloc(sizeof(struct Disk));
        disk->size = size;
        // Oops! No disk->next = NULL; here
        return disk;
    }
    
  • Unchecked memory allocation: If malloc fails (returns NULL) when creating a disk, your code might try to access invalid memory. Always add a check for this.
  • Missing input validation: If you're using user input to set disk sizes, not checking for non-positive values (0 or negatives) can break later logic (like trying to place a "negative size" disk).
Key Features You Might Have Missed for the Full Game

1. Peg Management with Linked Lists

  • Wrap each peg in a struct: Instead of managing three separate linked list heads, create a struct Peg to hold the peg's name (A/B/C) and the top of its disk list. This makes it way easier to pass pegs around in functions:
    struct Peg {
        char id; // e.g., 'A', 'B', 'C'
        struct Disk* top; // Points to the smallest disk on the peg
    };
    
  • Implement stack operations: Hanoi disks follow a LIFO rule (only move the top disk). You'll need push_disk (add to peg top, with validation that the new disk is smaller than the current top) and pop_disk (remove and return the top disk) functions tailored to your linked list structure.

2. Core Game Modes

Manual Solve Mode

  • Input handling & validation: When the user enters a move (e.g., "A to C"), you need to:
    • Check that the source peg isn't empty.
    • Verify the target peg's top disk (if any) is larger than the disk being moved.
    • Ensure the user entered valid peg IDs.
  • State visualization: After every move, print the current state of all three pegs. Write a print_pegs function that traverses each peg's linked list and displays disks (e.g., using ==== for size 4, == for size 2, etc.).

Auto Solve Mode

  • Recursive algorithm integration: The classic Hanoi recursive logic (move(n, source, aux, target)) needs to map directly to your linked list operations. Each recursive step should call pop_disk from the source and push_disk to the target, with optional print statements to show each move.
  • Stack overflow prevention: If you let users pick a very high disk count (like 20+), recursion depth might exceed the program's stack limit. Add a reasonable upper bound (e.g., 10) for auto-solve mode, or implement an iterative stack-based solution instead.

3. User Experience & Input Safety

  • Robust input validation: For disk count, make sure users enter a positive integer—reject non-numeric inputs, zero, and negatives with clear prompts. Same goes for mode selection (manual/auto) and move commands.
  • Error feedback: If the user tries an invalid move (like placing a big disk on a small one), don't just crash—print a friendly error message and let them try again.

4. Memory Cleanup

  • Free all allocated memory: At the end of the game, traverse each peg's linked list and free every disk node to avoid memory leaks. Write a helper function free_peg that handles this for a single peg, then call it for all three.
  • Handle mid-program errors: If something goes wrong (like a malloc failure during disk creation), make sure to free any already allocated nodes before exiting.

5. Edge Case Handling

  • Single disk scenario: Both modes should handle this trivial case smoothly (one move, no validation hoops).
  • Empty peg operations: Ensure your pop_disk function doesn't crash if someone tries to take a disk from an empty peg (return NULL or handle it gracefully).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:01:04