This is my AC code in C++


  • 0
    J
        /**
     * 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 || !head->next)
                return head;
            int count = 1;
            bool isHead = false;
            if (m == 1){
                isHead = true;
            }
            int len = n-m;
            if (len < 1)
                return head;
            ListNode *pre, *p;
            pre = p = head;
            while (--m && p){
                pre = p;
                p = p->next;
            }
            ListNode *h = pre,*tail = p, *next;
            pre = p;
            p = p->next;
            while (len-- && p){
                next = p->next;
                p->next = pre;
                pre = p;
                p = next;
            }
            if (isHead){
                head = pre;
            }else{
                h->next = pre;
            }
            tail->next = p;
            return head;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.