zoukankan      html  css  js  c++  java
  • leetcode--Reverse Linked List II

    1.题目描述

    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.
     
    Note:
    Given m, n satisfy the following condition:
    1 ? m ? n ? length of list.

    2.解法分析

    解法就是头插法的变形,稍微改动一下,确定一下边界条件就好了。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *reverseBetween(ListNode *head, int m, int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            
            if(m>=n)return head;
            if(!head)return NULL;
            
            int count=1;
            ListNode * cur=head;
            ListNode * start=NULL;
            ListNode * headPrev=NULL;
            while(count<m&&cur)
            {
                headPrev=cur;
                cur=cur->next;count++;
            }
            
            start=cur;
            while(count<n&&cur->next)
            {
                ListNode *temp = cur->next;
                cur->next=temp->next;
                temp->next=start;
                start=temp;
                if(headPrev)headPrev->next=start;
                count++;
            }
            
            if(headPrev)return head;
            else return start;
            
        }
    };

    这个题目很简单,但是我在上面竟然磨叽了一个小时,伤不起,究其原因,主要是两个while循环的判断条件打错了,写的条件和我脑海中想象的不一样,是这样的:

    我本意是while(count<m&&cur)却写成了while(count<m&&!cur),好吧,我决定以后写这种判断条件尽量写成cur!=NULL,免得出这种哭笑不得的错误。

  • 相关阅读:
    有个名字叫随便乱记——css3
    CSS3伸缩布局
    路政整理
    GIst
    SVN回滚版本
    你需要知道的CSS3 动画技术
    iScroll框架的使用和修改
    CSS3阴影 box-shadow的使用和技巧总结
    Javascript异步编程的4种方法
    zepto学习零碎
  • 原文地址:https://www.cnblogs.com/obama/p/3266083.html
Copyright © 2011-2022 走看看