• #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;
        }
    };
    

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

     

  • 相关阅读:
    课堂作业1
    懒人创造了方法
    四则运算
    动手动脑与原码反码补码
    java测试感受
    暑假进度报告四
    暑假进度报告三
    暑假进度报告二
    暑假进度报告一
    《大道至简》读后感
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10409250.html
Copyright © 2020-2023  润新知