1. Engineering
  2. Computer Science
  3. could someone explain as to why when i enter a...

Question: could someone explain as to why when i enter a...

Question details

Could someone explain as to why when I enter a sentence at the command line, for instance "1 2 3 4 5", it returns 5 4 3 2 1?I'm assuming it's a pointer error on my part, but again could some explain the error and modify the code to have it return in the correct order, I.E. "1 2 3 4 5" returns in that order. The language is C++. Also, to compile the program you must use -lreadline when compiling. Thanks.

#include
#include
#include
#include
#include
#include
#include

using namespace std;

struct Node{
char* data;
Node *next;
};   
  
struct Node *head = NULL;
int length = 0;

void addNode(char* data){
Node* newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = data;
newnode->next = head;
head = newnode;
length++; }
  
void print(){
Node* temp = head;
while(temp != NULL){
cout << "{" << temp->data << "}";
temp = temp->next;
}
}

int main(){
static char* line_input = readline("> ");
char* tok = strtok(line_input, " ");
while(tok != NULL){
addNode(tok);
tok = strtok(NULL, " ");
}
cout << "[";
print();
cout << "]";
}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution