linkedlist implementation in c++ code example
Example 1: linkedlist implementation in c++
#include
using namespace std;
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
};
int main()
{
linked_list a;
a.add_node(1);
a.add_node(2);
return 0;
}
Example 2: linked list in c++ stl
#include
#include
#include
#include
#define ll long long
using namespace std;
//function to print all the elements of the linked list
void showList(list l){
list :: iterator it; //create an iterator according to the data structure
for(it = l.begin(); it != l.end(); it++){
cout<<*it<<" ";
}
}
int main(){
list l1;
list l2;
for(int i=0; i<10; i++){
l1.push_back(i*2); //fill list 1 with multiples of 2
l2.push_back(i*3); //fill list 2 with multiples of 3
}
cout<<"content of list 1 is "<