struct Node
{
int data;
struct Node *next;
};
//insert a new node in an empty list
struct Node *insertInEmpty(struct Node *last, int new_data)
{
// if last is not null then list is not empty, so return
if (last != nullptr)
return last;
// allocate memory for node
struct Node *temp = new Node;
// Assign the data.
temp -> data = new_data;
last = temp;
// Create the link.
last->next = last;
return last;
}
//insert new node at the beginning of the list
struct Node *insertAtBegin(struct Node *last, int new_data)
{
//if list is empty then add the node by calling insertInEmpty
if (last == nullptr)
return insertInEmpty(last, new_data);
//else create a new node
struct Node *temp = new Node;
//set new data to node
temp -> data = new_data;
temp -> next = last -> next;
last -> next = temp;
return last;
}
you make a .h file with include guards, includes, and function headers inside it..
you do not need the keyword struct everywhere in c++. C spams it where it isnt needed a lot, so maybe you saw a C example?
you may want a *list* struct or class that has nodes and the list-methods rather than just a collection of loose functions.
c++ tends to use structs for small data wrappers and classes for objects, but you can use either for either is just convention. Class is private default, struct is public default, both can be overridden.
#ifndef linklist
#define linklist
#include<anything needed by c++ file>
struct node... ///put that in the header
//Node* node::insertAtBegin(struct Node *last, int new_data); //struct method header example
Node* insertAtBegin(struct Node *last, int new_data); //non member header