注意代码的鲁棒性!
函数:
1 ListNode* TheLastKthNode(ListNode* pHead,int k) 2 { 3 if(pHead==nullptr || k<=0) 4 return nullptr; 5 ListNode* quickNode=pHead; 6 ListNode* slowNode=pHead; 7 int cnt=1; 8 while(quickNode->m_pNext!=nullptr&&cntm_pNext;11 ++cnt;12 }13 if(cnt m_pNext!=nullptr)16 {17 quickNode=quickNode->m_pNext;18 slowNode=slowNode->m_pNext;19 }20 return slowNode;21 }
测试代码:
1 #include"List.h" 2 3 void Test(char* testName,ListNode* pHead,int k,int expect) 4 { 5 cout<<<":"; 6 ListNode* result=TheLastKthNode(pHead,k); 7 if(result==nullptr) 8 { 9 cout<<"Invalid input."< m_Value==expect)12 {13 cout<<"Passed."<