#pragma once
#include<iostream>
using namespace std;
template<typename T>
struct Node
{
T data;
Node<T>* next;
};
template<class T>
class LinkList
{
public:
LinkList();
~LinkList();
public:
bool ListInsert_head(int i,const T& e);
bool ListDelete(int i);
bool GetElem(int i,T&e);
int LocateElem(const T&e);
void DispList();
int ListLength();
bool Empty();
void ReverseList();
private:
Node<T>* m_head;
int m_length;
};
template<class T>
LinkList<T>::LinkList()
{
m_head = new Node<T>;
m_head->next = nullptr;
m_length = 0;
}
template<class T>
bool LinkList<T>::ListInsert_head(int i, const T& e)
{
if (i<1 || i>(m_length + 1))
{
cout << "插入位置不合法" << endl;
return false;
}
Node<T>* p_curr=m_head;
for (int j = 0; j < (i - 1); j++)
{
p_curr = p_curr->next;
}
Node<T>* node = new Node<T>;
node->data = e;
node->next = p_curr->next;
p_curr->next = node;
m_length++;
cout << "插入成功" << endl;
return true;
}
template<class T>
bool LinkList<T>::ListDelete(int i)
{
if (i<1 || i>(m_length + 1) || i < m_length)
{
cout << "删除位置不合法,或者链表为空" << endl;
return false;
}
Node<T>* p_curr = m_head;
for (int j = 0; j < (i - 1); j++)
{
p_curr = p_curr->next;
}
Node<T>* p_willdel = p_curr->next;
p_curr->next = p_willdel->next;
delete p_willdel;
m_length--;
cout << "删除成功" << endl;
return true;
}
template<class T>
bool LinkList<T>::GetElem(int i, T& e)
{
if (i<1 || i>(m_length + 1) || i < m_length)
{
cout << "查找位置不合法,或者链表为空" << endl;
return false;
}
Node<T>* p_curr = m_head;
for (int j = 0; j < (i - 1); j++)
{
p_curr = p_curr->next;
}
e = p_curr->data;
cout << "找到值:" << e << endl;
return true;
}
template<class T>
int LinkList<T>::LocateElem(const T& e)
{
Node<T>* p_curr = m_head;
for(int i=1; i<=m_length; i++)
{
if (p_curr->next->data == e)
{
cout << "找到了:" << p_curr->next->data << " ";
return i;
}
p_curr = p_curr->next;
}
cout << "找不到该值" << endl;
return -1;
}
template<class T>
void LinkList<T>::DispList()
{
Node<T>* p = m_head->next;
while (p != nullptr)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
template<class T>
int LinkList<T>::ListLength()
{
return m_length;
}
template<class T>
bool LinkList<T>::Empty()
{
if (m_head->next ==nullptr)
{
return true;
}
return false;
}
template<class T>
void LinkList<T>::ReverseList()
{
if ( 1>= m_length)
{
return ;
}
Node<T>* pptmp = m_head->next->next;
m_head->next->next = nullptr;
Node<T>* ptmp;
while (pptmp != nullptr)
{
ptmp = pptmp;
pptmp = pptmp->next;
ptmp->next = m_head->next;
m_head->next = ptmp;
}
}
template<class T>
LinkList<T>::~LinkList()
{
Node<T>* pnode = m_head->next;
Node<T>* ptmp;
while (ptmp != nullptr)
{
ptmp = pnode;
pnode = pnode->next;
delete ptmp;
}
delete m_head;
m_head = nullptr;
m_length = 0;
}
#include"List.hpp"
void test()
{
LinkList<int>lk;
lk.ListInsert_head(1, 12);
lk.ListInsert_head(2, 22);
lk.ReverseList();
lk.DispList();
}
int main()
{
test();
system("pause");
return 0;
}