zoukankan      html  css  js  c++  java
  • 【leetcode】Reverse Linked List II (middle)

    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;
        }
  • 相关阅读:
    python-禅
    学习思路(待完善)
    思考-想法-研究生
    五一前随笔
    监督学习,非监督学习和半监督学习
    第二章maven的安装和配置
    maven实战 第一章
    常用接口测试工具
    jmeter监控服务器性能(转载)
    数据库操作
  • 原文地址:https://www.cnblogs.com/dplearning/p/4333778.html
Copyright © 2011-2022 走看看