C++链表实现

来源:互联网 发布:php ahp和jhp 编辑:程序博客网 时间:2024/05/29 15:17

总结了一下最近学的东西,比如模板,链表。实现了初始化,任意位置插入,头插和尾插,删除指定位置元素,打印链表。没有做删除整表,拷贝构造等部分,有空再写。写的不好,乱七八糟的。大伙将就着看吧。能当一个参考。

#include <iostream>using namespace std;template<class T>class List{protected:struct _list{T data;_list* pNEXT;};typedef _list LIST, *PLIST;public:List() :phead(NULL), pre(NULL){   Lenth = 0;}   size_t size()   {   return Lenth;   }   T getat(size_t index)const;   bool insert(size_t i, T&x)   {   if (i<0 || i>Lenth + 1)   return false;   size_t j = 0;   PLIST p = phead, s;   while (p&&j < i - 2)//p是指向链表的指针为什么会是空呢?答案在三行后.最终,p指向要求的前一个节点。因为在第四个处添加要求第四个变第五个。   {   j++;   p = p->pNEXT;   }   s = new LIST;   s->pNEXT = p->pNEXT;   p->pNEXT = s;   s->data = x;   Lenth++;   return 1;   }   bool delte(size_t i)   {   if (i<0 || i>Lenth + 1)   return false;   size_t j = 0;   PLIST p = phead;   while (p&&j < i - 2)   {   j++;   p = p->pNEXT;   }   //PLIST t = p;   p->pNEXT = p->pNEXT->pNEXT;   delete p;   Lenth--;   return 1;   }   List & push_front(T&x)   {   PLIST p = new LIST;   p->pNEXT = phead;   phead = p;   pre = p;   p->data = x;   Lenth++;   return *this;   }   void show()   {   PLIST p;   p = phead;   while (p)   {   cout << p->data << endl;   p = p->pNEXT;   }   }   List & push_back(T&x)   {   PLIST p = new LIST;   if (phead == NULL)   {   phead = p;   pre = p;     }   else   {   pre->pNEXT = p;   }   p->pNEXT = NULL;   p->data = x;   Lenth++;   return *this;   }private:size_t Lenth;PLIST phead;PLIST pre;};template<class T>T List<T>::getat(size_t index) const{PLIST p = phead;for (int i = 0; i < index; i++)p = p->pNEXT;return p->data;}


0 0
原创粉丝点击