21:调整数组顺序使奇数位于偶数前面
题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分。
void Reorder(int *pData, unsigned int length, bool (*func)(int))
{
if(pData == nullptr || length == 0)
return;
int *pBegin = pData;
int *pEnd = pData + length - 1;
while(pBegin < pEnd)
{
// 向后移动pBegin
while(pBegin < pEnd && !func(*pBegin))
pBegin ++;
// 向前移动pEnd
while(pBegin < pEnd && func(*pEnd))
pEnd --;
if(pBegin < pEnd)
{
int temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
}
}
}
bool isEven(int n)
{
return (n & 1) == 0;
}
22:链表中倒数第k个节点
题目:输入一个链表,输出该链表中倒数第k个结点。
//双指针,指针距离为k
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k)
{
if(pListHead == nullptr || k == 0)
return nullptr;
ListNode *pAhead = pListHead;
ListNode *pBehind = nullptr;
for(unsigned int i = 0; i < k - 1; ++ i)
{
if(pAhead->m_pNext != nullptr) //注意
pAhead = pAhead->m_pNext;
else
{
return nullptr;
}
}
pBehind = pListHead;
while(pAhead->m_pNext != nullptr)
{
pAhead = pAhead->m_pNext;
pBehind = pBehind->m_pNext;
}
return pBehind;
}
23:链表中环的入口节点
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
/* 断链
if(pHead==NULL||pHead->next==NULL) return NULL;
ListNode* fast=pHead->next;
ListNode* slow=pHead;
while(fast!=NULL)
{
slow->next=NULL;
slow=fast;
fast=fast->next;
}
return slow;
*/
// 2倍速度追赶
if(pHead==NULL||pHead->next==NULL) return NULL;
ListNode* fast=pHead;
ListNode* slow=pHead;
ListNode* cur=pHead;
while(fast!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
while(cur!=slow)
{
cur=cur->next;
slow=slow->next;
}
return cur;
}
}
return NULL;
}
24:反转链表
输入一个链表,反转链表后,输出新链表的表头。
ListNode* ReverseList(ListNode* pHead) {
if(pHead==nullptr||pHead->next==nullptr) return pHead;
ListNode* pre=nullptr;
ListNode* cur=pHead;
while(cur!=nullptr)
{
ListNode* next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}