Confusion/Dilemma -Question About Data Structure Pointers

I am noob to data structres right now,sorry if this does not makes sense at all,idk it's just been bugging me.


I have a question let us say we have the following Node definition
1
2
3
4
5
6
struct Node
{
int age;
Node *link;
};
Node *top = NULL;


and now i create a new node,There are 2 ways i could do this first one is:
1
2
3
4
5
Node *stk = new Node;

    stk -> link = NULL;
    cout << "\nEnter The Age : ";
    cin >> stk->age;
I have taken input directly into the Node's Age Variable.

Second Way
1
2
3
4
5
6
Node *temp = new Node;
int data;
temp -> link = NULL;
cout << "\nEnter The Data : ";
    cin >> data;
temp->age = data;

In this I created A temp pointer and used it.

Which is better and why?
Last edited on
well the long answer is probably neither.

the long answer is that you would have a method in the user-class (looks like a linked list class here) that does this stuff, and it would probably use a hybrid of methods 1 and 2. You want to avoid unnecessary extra variable creation (esp objects) and copying, so note*temp has no purpose, nor does data. But if you were to do validations, you might have "string data;" (read the input as a string, validate it, if its good, continue else ask for data until good) and that your new operations succeeded (here, you can just use the direct pointer though, you don't need an intermediate variable).

and the short answer:
method 1 is better for this snippet. Method 2 accomplishes nothing except wasting time and space. If you can justify the intermediate steps, then you do it. If you cannot, do not. The justification for a string data intermediate is to handle bad user input of 'abc' when you asked for an integer; the string is a different type than the true target (integer).

Last edited on
Thank You. Cleared things up a little.
Topic archived. No new replies allowed.