Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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);
}```


>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading