Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
思路:
好困啊,脑子晕晕的。 转了半天AC了。但写的很罗嗦,要学习大神的写法。 注意翻转的写法。
用伪头部
大神14行简洁代码
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(m==n)return head;
n-=m;
ListNode prehead();
prehead.next=head;
ListNode* pre=&prehead;
while(--m)pre=pre->next;
ListNode* pstart=pre->next;
while(n--)
{
ListNode *p=pstart->next;
pstart->next=p->next;
p->next=pre->next;
pre->next=p;
}
return prehead.next;
}
我的繁琐代码
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode fakehead();
ListNode * p = &fakehead;
for(int i = ; i < m; i++)
{
p = p->next = head;
head = head->next;
}
p->next = NULL; //m前的那一节末尾 ListNode *ptail = head; //翻转那一段的尾巴
ListNode *p1 = head, *p2 = NULL, *p3 = NULL;
if(p1->next != NULL)
{
p2 = p1->next;
}
p1->next = NULL;
for(int i = m; i < n; i++)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
} p->next = p1;
ptail->next = p2; return fakehead.next;
}