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

C++链表功能实现求助:用户输入管理、多链表创建及数值求和

Got it, let's fix your linked list program to match exactly what you're looking for. Here's a revised implementation along with explanations of the key changes:

Complete Revised Code

#include <iostream>
#include <string>
#include <algorithm> // For string reversal
using namespace std;

struct Node {
    string data;
    Node* next;
    Node() : next(nullptr) {} // Constructor to initialize next pointer
};

// Helper function to generate the full number string from the linked list
string getFormattedListString(Node* head) {
    string rawString;
    Node* current = head->next; // Skip the dummy head node
    
    // Traverse the list to collect characters (order is reverse of input sequence)
    while (current != nullptr) {
        rawString += current->data;
        current = current->next;
    }
    
    // Reverse to get the correct input order for display
    reverse(rawString.begin(), rawString.end());
    return rawString;
}

// Helper function to convert linked list to a numeric value
long long convertListToNumber(Node* head) {
    string numString = getFormattedListString(head);
    return stoll(numString); // Use long long to avoid integer overflow
}

// Helper function to add a new node to the HEAD of the linked list
void addNodeToHead(Node* head, const string& value) {
    Node* newNode = new Node;
    newNode->data = value;
    newNode->next = head->next;
    head->next = newNode;
}

int main() {
    // Initialize first linked list with a dummy head node
    Node* list1 = new Node;
    Node* currentWorkingList = list1;
    Node* list2 = nullptr; // Second list starts uninitialized

    string userInput;
    while (true) {
        cout << "Enter a number(quit to stop, + for new list, = to calculate): ";
        cin >> userInput;

        if (userInput == "quit") {
            break;
        } else if (userInput == "+") {
            // Create second list if it doesn't exist yet
            if (list2 == nullptr) {
                list2 = new Node;
                currentWorkingList = list2;
                cout << "New list created, start entering numbers.\n";
            } else {
                cout << "Second list already exists!\n";
            }
        } else if (userInput == "=") {
            // Check if both lists are available before calculating
            if (list2 == nullptr) {
                cout << "Please create a second list first using '+'\n";
                continue;
            }
            long long num1 = convertListToNumber(list1);
            long long num2 = convertListToNumber(list2);
            long long sum = num1 + num2;
            cout << num1 << " + " << num2 << " = " << sum << endl;
        } else {
            // Add input to current list and display the formatted string
            addNodeToHead(currentWorkingList, userInput);
            cout << getFormattedListString(currentWorkingList) << endl;
        }
    }

    // Note: In a production program, you'd add code here to free all allocated nodes
    // to avoid memory leaks. For simplicity, this is omitted here.

    return 0;
}

Key Changes Explained

  1. Removed the unnecessary menu system
    Your original code forced users to select "1. add to list" every time, which didn't match your requirement of direct input. The revised code loops continuously to accept input directly.

  2. Added helper functions for cleaner logic

    • addNodeToHead: Reusable function to handle inserting nodes at the head of the list (matches your requirement of adding input to the list head).
    • getFormattedListString: Traverses the list, collects the raw character sequence (which is reversed since we add to the head), then reverses it to display the input order (e.g., input 3 → 4 → 5 gives a raw list of 5→4→3, reversed to "345").
    • convertListToNumber: Converts the formatted string to a long long to handle larger numbers and avoid integer overflow.
  3. Added support for multiple lists

    • list1 and list2 track the two number lists.
    • currentWorkingList keeps track of which list we're adding input to. When you enter +, it initializes the second list and switches to it.
  4. Handled special inputs correctly

    • +: Creates a new list only if it doesn't already exist.
    • = : Checks if both lists exist, converts them to numbers, adds them, and prints the result.
    • quit: Exits the program cleanly.

Test Output (Matches Your Expected Output)

Enter a number(quit to stop, + for new list, = to calculate): 3
3
Enter a number(quit to stop, + for new list, = to calculate): 4
34
Enter a number(quit to stop, + for new list, = to calculate): 5
345
Enter a number(quit to stop, + for new list, = to calculate): +
New list created, start entering numbers.
Enter a number(quit to stop, + for new list, = to calculate): 1
1
Enter a number(quit to stop, + for new list, = to calculate): 2
12
Enter a number(quit to stop, + for new list, = to calculate): =
345 + 12 = 357

Quick Notes

  • The code uses a dummy head node for each list (a node that doesn't store data) to simplify edge cases like empty lists.
  • Memory cleanup is omitted here for simplicity—for a real application, you should traverse each list and delete every node to avoid memory leaks.
  • This assumes you're entering single-digit numbers. If you need to support multi-digit inputs, you'd need to adjust the logic to handle that (but your expected output suggests single-digit inputs are what you want).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:19:07