LeetCode-Reverse Linked List II

来源:互联网 发布:怎么做淘宝网 编辑:程序博客网 时间:2024/05/05 09:15
/** * 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 (head == NULL || head->next == NULL || m == n)        {            return head;        }        ListNode *last = new ListNode(0);        last->next = head;        ListNode *last1 = last;        for (int i = 0; i < m - 1; ++i)        {            last = last->next;        }        ListNode *pBeg = last->next;        ListNode *p = pBeg->next;        ListNode *pPre = pBeg;        for (int i = 0; i < n - m; ++i)        {            ListNode *pNext = p->next;            p->next = pPre;            pPre = p;            p = pNext;        }        last->next = pPre;        pBeg->next = p;        head = m == 1 ? last->next : head;        delete last1;        last1 = NULL;        return head;    }};


原创粉丝点击