0

In Data structure ad algorithm There are various linked list operations that allow us to perform different actions on linked lists includes the insertion operation which adds a new element to the linked list.

this example here demonstrates the implementation of linked list operation in C programming language , however the same logic / idea can also be implemented in C ++ ,

assume we want to implement this logic with c++ , what will be alternative to this line in c++?

malloc(sizeof(struct node));

struct node *newNode;
    newNode = malloc(sizeof(struct node));
    newNode->data = 4;
    newNode->next = head;
    head = newNode;
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
willy
  • 249
  • 3
  • 12
  • 2
    *Data structure alternative* -- Your issue is not a "data structures" one. Do you know what `malloc` does? If you do, you then should know what `new` does in C++. – PaulMcKenzie Dec 05 '22 at 13:44
  • 1
    the alternative in C++ is to use `std::list` (or `std::vector`) – 463035818_is_not_an_ai Dec 05 '22 at 13:46
  • ```std::shared_ptr newNode = std::make_shared();``` Can also used for creating new object without thinking the deletion of the object. But node should be defined as a class. However if you insist to use value type with struct you should be aware of delete of all objects. – Nazim Dec 05 '22 at 13:54

1 Answers1

0

Try node *newNode = new node();