寻找单项链表中间那个元素,如果有两个则取前面一个。
1 #include <iostream> 2 #include <cassert> 3 4 using namespace std; 5 6 template<typename T> 7 struct Node 8 { 9 T m_nData; 10 Node<T> *m_pNext; 11 }; 12 13 template<typename T> 14 Node<T>* createList(const T myArray[], const int &n) 15 //创建链表 16 { 17 assert(myArray && n >0); 18 Node<T>* pHead = new Node<T>; 19 Node<T>* pNew = NULL; 20 pHead->m_pNext = NULL; 21 for (int i = 0; i < n; i++) 22 { 23 pNew = new Node<T>; 24 pNew->m_nData = myArray[i]; 25 pNew->m_pNext = pHead ->m_pNext; 26 pHead->m_pNext = pNew; 27 } 28 return pHead; 29 } 30 31 template<typename T> 32 Node<T>* retMiddle(Node<T>* myList) 33 //获取中间元素 34 { 35 assert(myList); 36 Node<T> *p = myList->m_pNext; 37 Node<T> *q = myList->m_pNext; 38 while (q->m_pNext && q->m_pNext->m_pNext) 39 { 40 p = p->m_pNext; 41 q = q->m_pNext->m_pNext; 42 } 43 return p; 44 } 45 46 template<typename T> 47 void printList(Node<T>* myList) 48 //打印链表 49 { 50 assert(myList); 51 Node<T>*p = myList->m_pNext; 52 cout<<"List: "; 53 while (p) 54 { 55 cout<<p->m_nData<<" "; 56 p = p->m_pNext; 57 } 58 cout<<endl; 59 } 60 void main() 61 { 62 const int n = 2; 63 const int myArray[n] = {1, 2}; 64 Node<int>* myList; 65 Node<int>* mymiddle; 66 myList = createList(myArray, n); 67 printList(myList); 68 mymiddle = retMiddle(myList); 69 cout<<"Middle: "<<mymiddle->m_nData<<endl; 70 system("pause"); 71 return; 72 }