Classes

Hi! I would like to ask how to create this to a header file and implement it on a cpp file?

This is a linked list code by the way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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

#endif

Last edited on
Topic archived. No new replies allowed.