linked list creation in c++ code example
Example 1: linked list in c++ stl
#include <bits/stdc++.h>
#include <iostream>
#include <list>
#include <iterator>
#define ll long long
using namespace std;
void showList(list <int> l){
list <int> :: iterator it;
for(it = l.begin(); it != l.end(); it++){
cout<<*it<<" ";
}
}
int main(){
list <int> l1;
list <int> l2;
for(int i=0; i<10; i++){
l1.push_back(i*2);
l2.push_back(i*3);
}
cout<<"content of list 1 is "<<endl;
showList(l1);
cout<<endl;
cout<<"content of list 2 is "<<endl;
showList(l2);
cout<<endl;
l1.reverse();
showList(l1);
cout<<endl;
l1.sort();
showList(l1);
cout<<endl;
l2.pop_front();
l2.pop_back();
l2.push_back(10);
l2.push_front(20);
return 0;
}
Example 2: linked list class c++ basic implementation
template<typename T>
class list {
public:
struct node {
T value;
node* next;
};
list() : hd(nullptr), tl(nullptr) {}
node* head() { return hd; }
node* tail() { return tl; }
void insert(node* prior, T value);
node* at(int i);
void erase(node* prior);
void clear();
void push_back(T value);
void pop_back();
void push_front(T value);
void pop_front();
int size();
private:
node* hd, tl;
}