zoukankan      html  css  js  c++  java
  • #Leetcode# 92. Reverse Linked List II

    https://leetcode.com/problems/reverse-linked-list-ii/

    Reverse a linked list from position m to n. Do it in one-pass.

    Note: 1 ≤ m ≤ n ≤ length of list.

    Example:

    Input: 1->2->3->4->5->NULL, m = 2, n = 4
    Output: 1->4->3->2->5->NULL

    代码:

    /**
     * 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) {
            if(!head) return NULL;
            int num = m - 1;
            ListNode *dummy = new ListNode(-1);
            ListNode *st = dummy, *ans = st;;
            dummy -> next = head;
            ListNode *slow = head;
            n -= m, m -= 1;
            while(m --) slow = slow -> next;
            ListNode *cur = slow;
            while(n --) cur = cur -> next;
            ListNode *end = cur -> next;
            cur -> next = NULL;
            slow = reverseList(slow);
            ListNode *fast = slow;
            while(fast -> next) fast = fast -> next;
            fast -> next = end;
            while(num --) st = st -> next;
            st -> next = slow;
            return ans -> next;
        }
        
        ListNode *reverseList(ListNode *c) {
            if(!c || !c -> next) return c;
            ListNode *New = reverseList(c -> next);
            c -> next -> next = c;
            c -> next = NULL;
            return New;
        }
    };
    

      分三段 然后拼在一起 但是写的乱糟糟 大概写了一个多小时 我恨!自己不争气 落泪

     

  • 相关阅读:
    javascript Date.prototype
    Mac 安装node.js
    element-ui适配pad 遇到的问题
    GCD实现异步任务同步的两种方式
    颜色判断
    ARC下方法重复问题
    检查IDFA的方法
    mac 下安装ecplise
    注释使用
    Xcode 8.0 控制台打印问题解决办法
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10409250.html
Copyright © 2011-2022 走看看