码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Reverse Linked List II (middle)

时间:2015-03-12 22:12:16      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

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->NULLm = 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(0);
    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(0);
        ListNode * p = &fakehead;
        for(int i = 1; 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;
    }

 

【leetcode】Reverse Linked List II (middle)

标签:

原文地址:http://www.cnblogs.com/dplearning/p/4333778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!