题目:给出一个链表和一个数k, 比如链表1→2→3→4→5→6;
若k=2, 则翻转后2→1→4→3→6→5;
若k=3, 则翻转后3→2→1→6→5→4;
若k=4, 则翻转后4→3→2→1→5→6;
用程序实现.
方法1分析:
将链表以k单位划分,分别倒序再链接;
方法1实现:
/*反转链表*/
ListNode* ReverseList (ListNode* pHead, ListNode* pTail)
{
ListNode* pReversedHead = NULL;
ListNode* pNode = pHead;
ListNode* pPrev = NULL;
while (pNode != pTail)
{
ListNode* pNext = pNode->m_pNext;
if(pNext == pTail)
pReversedHead = pNode;
pNode->m_pNext = pPrev;
pPrev = pNode;
pNode = pNext;
}
return pReversedHead;
}
/*K链表翻转*/
ListNode* KReverseList (const int k, ListNode* pHead)
{
ListNode* pReversedList = NULL;
ListNode* pReversedTail = NULL;
int index = 0;
ListNode* pStart = pHead; //起始结点
ListNode* pEnd = pHead; //结尾结点
for(int i=0; i<k; ++i) {
pEnd = pEnd->m_pNext;
if(pEnd == NULL)
break;
}
pReversedList = ReverseList (pStart, pEnd);
pReversedTail = pStart;
pStart = pEnd;
while (1)
{
if(pEnd == NULL)
break;
pEnd = pEnd->m_pNext;
++index;
if (index%k == 0) {
ListNode* pTemp = ReverseList (pStart, pEnd);
pReversedTail->m_pNext = pTemp;
pReversedTail = pStart;
pStart = pEnd;
}
}
if (pStart != NULL)
pReversedTail->m_pNext = pStart;
return pReversedList;
}