题解 | #链表内指定区间反转#

链表内指定区间反转

http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

这道题的思路其实简单,看到了空间复杂度可以是O(N),瞬间就想到了用一个指针数组来存每一个node的地址,然后用一个int数组存变换前和变换后数组index的对应关系(原序号0,1,2,3,4,变换后序号可能就是0,3,2,1,4),然后将其全部串在一起就行了

 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        // write code here
        if(m == n)
            return head;
        if(n-m==0)
            return head;
        if(head == NULL||head->next == NULL)
            return head;
        ListNode* node = new ListNode(-1);
        ListNode* cur = node;
        ListNode* once = head;
        ListNode *a[1100];
        int b[1100] = {0};
        int i = 0 ;
        
        while(once)
        {
            a[i] = once;
            once = once->next;
            if(m-1<=i&&i<=n-1)
            {
                //cout<<"i = "<<i<<endl;
                b[i] = m+n-i-2;
                //cout<<"b[i] = "<<b[i]<<endl;
            }
            else
                b[i] = i;
            i++;
        }
        int j = 0 ;
        while(j<i)
        {
            cur->next = a[b[j]];
            cur = cur->next;
            j++;
        }
        cur->next = NULL;
        return node->next;
        
       
    }
};
全部评论

相关推荐

07-11 11:15
中南大学 Java
好可爱的hr姐姐哈哈哈哈
黑皮白袜臭脚体育生:兄弟们貂蝉在一起,吕布开了
点赞 评论 收藏
分享
牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务