反转链表
给出一个链表和一个数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,
//用程序实现Node* RotateList(Node* list, size_t k). 提示:这个题是链表逆置的升级变型。
解法思路:
1.先反转前K个节点,保存后面的链表头,返回反转后的链表头;
2.递归反转后面链表
3.将每次反转后的链表连接在一起(每次传进来的链表头正好是反转后的链表尾)
struct ListNode
{
ListNode* _next;
int _data;
};
ListNode* Reverse(ListNode* phead,ListNode* ptail)//反转phead到ptail的链表,返回链表的头节点
{
assert(phead);
assert(ptail);
if (phead==ptail)
{
return ;
}
ListNode* pre=NULL;
ListNode* cur=phead;
ListNode* next=NULL;
while (cur!=ptail)
{
next=cur->_next;
cur->_next=pre;
pre=cur;
cur=next;
}
cur->_next=pre;
return cur;
}
ListNode* ReverseK(ListNode* phead,const int k)
{
if (phead==NULL)
{
return ;
}
ListNode* pcur=phead;
int i=k;
while (--i)
{
pcur=pcur->_next;
if (pcur==NULL)
{
return ;
}
}
ListNode* ptail=pcur;
ListNode* pprelist=Reverse(phead,ptail);//反转前K个节点,保存链表头
ListNode* plist=pcur->_next;
ListNode* pprehead=ReverseK(plist,k);//反转后面的链表
phead->_next=pprehead;//链接链表
return pprelist;
}