C++ linkedlist
#include <iostream>
#include <string>
using namespace std;
template <typename T>
struct Value
{
T m_Value;
Value(){ m_Value=0;}
};
template <>
struct Value <string>
{
string m_Value;
Value(){ m_Value.assign("");}
};
template <typename T>
struct Node
{
Node();
Value<T> m_Value;
Node<T>* m_Prev;
Node<T>* m_Next;
};
template <typename T>
Node<T>::Node()
{
m_Prev=nullptr;
m_Next=nullptr;
}
template <typename T>
class LinkedList
{
private:
Node<T>* m_Head;
Node<T>* m_Tail;
bool m_IsEmpty;
public:
LinkedList();
bool push_back(T val);
bool push_front(T val);
bool pop_back();
bool pop_front();
bool printList();
};
template <typename T>
LinkedList<T>::LinkedList():
m_Head(nullptr),
m_Tail(nullptr),
m_IsEmpty(true)
{}
template <typename T>
bool LinkedList<T>::pushback(T val)
{
Node<T>* node=new Node<T>;
node->m_Value.m_Value=val;
if (m_IsEmpty==false)
{
m_Tail->m_Next=node;
node->m_Prev=m_Tail;
m_Tail=node;
}
else
{
m_Head = m_Tail = node;
m_IsEmpty = false;
}
return true;
}
template <typename T>
bool LinkedList<T>::pushfront(T val)
{
Node<T> node=new Node<T>;
node->m_Value.m_Value=val;
if (m_IsEmpty==false)
{
m_Head->m_Prev = node;
node->m_Next=m_Head;
m_Head=node;
}
else
{
m_Head=m_Tail=node;
m_IsEmpty = false;
}
return true;
}
template <typename T>
bool LinkList<T>::popback()
{
if (m_IsEmpyt==false)
{
Node<T>* delnode = m_Tail;
m_Tail = m_Tail->m_Prev;
if(m_Tail==nullptr)
{
m_Head=nullptr;
m_IsEmpty = true;
}
m_Tail->m_Next=nullptr;
if(delnode)
{
delete delNode;
delNode = nullptr;
}
}
else
{
cout<<"Failed:No element in LinkedList."<<endl;
return false;
}
return true;
}
template <typename T>
bool LinkedList<T> popfront()
{
if (m_IsEmpty==false)
{
Node<T>* delnode=m_Head;
m_Head=m_Head->m_Next;
if(m_Head==nullptr)
{
m_Tail=nullptr;
m_IsEmpty=true;
}
m_Head->m_Prev = nullptr;
if(delnode)
{
delete delnode;
delnode=nullptr;
}
}
else
{
cout<<"Failed:No element in LinkedList."<<endl;
return false;
}
return true;
}
template <typename T>
bool LinkedList<T>::printList()
{
Node<T>* node=m_Head;
while(node)
{
cout<<node->m_Value.m_Value<<" ->";
node=node->m_Next;
}
cout<<"nullptr"<<endl;
return true;
}
void InsertIntData()
{
LinkedList<int> mylist;
mylist.push_back(1);
mylist.push_back(2);
mylist.push_back(3);
mylist.printList();
}
void InsertStrData()
{
LinkedList<string> mylist;
mylist.push_back('hello');
mylist.push_back(' ');
mylist.push_back('world');
mylist.printList();
}
int main()
{
InsertIntData();
InsertStrData();
return 0;
}