abhinav700's blog

By abhinav700, history, 12 months ago, In English

While declaring a link list, why do we create a new Node using Node* node = new Node(value) ? Can't we simply use Node node(val) if not, then why? and if we can, what are changes to our code we will have to make while using later syntax, for basic operations on link lists?

I was revising link list, and although I can solve the questions, I was confused with this syntax.

  • Vote: I like it
  • -21
  • Vote: I do not like it

»
12 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Node node(val);
allocates memory in the stack, can't be used after the function completes

Node* node = new Node(val); allocates memory in the heap, and can be used until delete is called

This post is heavily downvoted because this is a basic thing to know before trying to implement linked lists.