Home > Net >  I read the input number with getchar(), why is the number reversed in the linked list?
I read the input number with getchar(), why is the number reversed in the linked list?

Time:10-16

I typed 1234, but the list has 4,3,2,1 in it. I suspect the problem is getchar() itself, or a function in the class, but I have no way to find out.
The link class is responsible for some linked list operations, such as deletion, insertion, etc., while the node class is responsible for creating and assigning nodes.
The createlist class is responsible for the creation of the linked list, which is the main source of the problem. I wrote the debug statement in it, so you can run it and see the results for yourself

using namespace std;

class Node
{
public:
    int data;
    Node *next;
    Node()
    {
        next = nullptr;
    }
    Node(int data)
    {
        this->data = data;
    }
    Node(const Node &temp)
    {
        this->data = temp.data;
    }
};

class Link
{
public:
    Node *head;
    int length = 0;
    Link()
    {
        head = new Node();
    }
    ~Link()
    {   
        while (head != nullptr)
        {
            Node *p = head->next;
            free(head);
            head = p;
        }
    }
    void insert(const Node &cache)
    {
        Node *temp = new Node(cache);
        temp->next = head->next;
        head->next = temp;
        length  ;
    }
};

void Creatlist(Link &link) 
{
    char cache;
    while (1)
    {
        cache = getchar();
        if (cache == '\n')
            break;
        link.insert(Node(cache - '0'));
        cout << cache << " ";
    }
    cout<<endl;
    Node *p = link.head->next;
    cout << "in the linklist:";
    while (p != nullptr)
    {
        cout << p->data << " ";
        p = p->next;
    }
}

int main()
{
    Link link;
    cout<<"inut numbers:"<<endl;
    Creatlist(link);
}```


CodePudding user response:

With the insert you inserted to the FRONT of the list. So you had "1", then "2->1" ... If you want to insert to the end, don't insert at the head, but hake a Node* tail in the class Link and an insert_end function as

//...
Node* temp;
void insert_end(const Node &cache){
    Node *temp = new Node(cache);
    tail->next=temp;
    tail=tail->next;
    length  ;
}

Alsoin the constructor set tail=head

  •  Tags:  
  • c
  • Related