在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
代码如下
View Code
1 #include <iostream> 2 #include <fstream> 3 #include <sstream> 4 5 using namespace std; 6 class Student 7 { 8 public: 9 int sId; 10 char sName[10]; 11 }; 12 13 //申明模版类 14 template <typename T> 15 class Link 16 { 17 private: 18 Link * pHead; 19 Link * pCur; 20 Link * pPrev; 21 Link * pNext; 22 T node; 23 int iSize; 24 public: 25 Link() 26 { 27 pHead = NULL; 28 pCur = NULL; 29 pPrev = NULL; 30 iSize = 0; 31 } 32 void push(T& node); 33 int deleteNode(T& node); 34 T searchNode(T& node); 35 }; 36 37 //定义类模版函数 38 template<class T> 39 void Link<T>::push(T& node) 40 { 41 if(pHead == NULL) 42 { 43 pCur = new Link; 44 pCur->pNext = NULL; 45 pHead = pCur; 46 pPrev = pHead; 47 } 48 else 49 { 50 pCur = new Link; 51 pCur->pNext = NULL; 52 53 pPrev->pNext = pCur; 54 pPrev = pCur; 55 } 56 pCur->node = node; 57 iSize ++; 58 } 59 60 template<class T> 61 int Link<T>::deleteNode(T& node) 62 { 63 int flag = 0; 64 Link *pTemp = pHead; 65 Link *pPrev = pHead; 66 while(pTemp != NULL) 67 { 68 if(pTemp->node.sId == node.sId) 69 { 70 if(pTemp == pHead) 71 { 72 pHead = pHead->pNext; 73 } 74 else if(pTemp->pNext == NULL) 75 { 76 pPrev->pNext = pTemp->pNext; 77 } 78 else 79 { 80 pPrev->pNext = pTemp->pNext; 81 } 82 flag = 1; 83 } 84 if(pTemp == pHead) 85 { 86 pPrev = pHead; 87 } 88 else 89 { 90 pTemp = pTemp->pNext; 91 pPrev = pPrev->pNext; 92 } 93 } 94 iSize --; 95 return flag; 96 } 97 98 template<class T> 99 T Link<T>::searchNode(T& node) 100 { 101 Link *pTemp = pHead; 102 Link *pPrev = pHead; 103 while(pTemp != NULL) 104 { 105 if(pTemp->node.sId == node.sId) 106 { 107 return pTemp->node; 108 } 109 pTemp = pTemp->pNext; 110 } 111 } 112 113 void operator <<(ostream&,Student s) 114 { 115 cout<<s.sId<<" "<<s.sName<<endl; 116 } 117 118 int main() 119 { 120 Student s1,s2,temp; 121 s1.sId = 10; 122 strcpy(s1.sName,"xxx"); 123 s2.sId=2; 124 strcpy(s2.sName,"jack"); 125 Link<Student> link; 126 link.push(s1); 127 link.push(s2); 128 temp = link.searchNode(s2); 129 cout<<temp; 130 cout<<temp.sName<<endl; 131 return 0; 132 } s |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论