逆转链表

每K个元素逆转一次。

这段代码是从某节点开始逆转K个

ListNode Reverse(ListNode head,ListNode* tail,int count)
{
ListNode
pre = NULL;
ListNode p = head;
ListNode
q = head->next;
int num = count;
if(q == NULL)
return p;
if(count <= 1)
return p;
while(p&& count–)
{
p->next = pre;
pre = p;
p = q;
if(q != NULL)
q = q->next;
else
break;
}
if(count == 0 && !p || count == -1)
{
//complete reverse
head->next = p;
*tail = head;
head = pre;
return pre;

}
else
{
//reverse back
*tail =head;
head = pre;
head=Reverse(head,tail,num-count);
return head;
}

}

//真正的逆转函数

ListNode ReverseK(ListNode head, int count)
{

ListNode pre=NULL;
ListNode
p = head;
ListNode q = head->next;
ListNode
tail = NULL;
ListNode* newHead = Reverse(head,&tail,count);

int num = count;
tail = head;
head = head->next;
ListNode* newTail = tail;
while(head)
{

head = Reverse(head,&tail,count);
newTail->next = head;
head = tail->next;
newTail = tail;
tail = tail->next;

}
return newHead;
}

  • 本文作者: 帐前卒
  • 本文链接: http://chillyc.info/2008/2009865/
  • 版权声明: 本博客所有文章除特别声明外,只能复制超链接地址,且必须注明出处!