链表节点类定义:
1 template <class T> 2 class SingleList; 3 template <class T> 4 class Node 5 { 6 private: 7 T element; 8 Node<T> *link; 9 friend class SingleList<T>; 10 };
链表类定义:
1 template <class T> 2 class SingleList :public LinearList<T> 3 { 4 public: 5 SingleList() 6 { 7 first = NULL; 8 n = 0; 9 } 10 ~SingleList(); 11 bool SM_Delete(T x); 12 private: 13 Node<T>* first; 14 };
删除特定元素X的成员函数:
方法一:
1 template<class T> 2 bool SingleList<T>::SM_Delete(T x) 3 { 4 Node<T> *p; 5 int j = 0; 6 p = first; 7 while (p) 8 { 9 for (j = 0; p&&p->element != x; j++) 10 p = p->link; 11 if (p) 12 { 13 Delete(j); 14 p = first; 15 } 16 else 17 return false; 18 } 19 return true; 20 }
方法二:
1 template<class T> 2 bool SingleList<T>::SM_Delete(T x) 3 { 4 for (Node<T>** cur = &first; *cur;) 5 { 6 Node<T>* entry = *cur; 7 if (entryement == x) 8 { 9 *cur = entry->link; 10 free(entry); 11 } 12 else 13 cur = &entry->link; 14 } 15 }
时间: 2024-10-18 23:14:42