[LeetCode]92. Reverse Linked List II

来源:互联网 发布:vscode terminal 编辑:程序博客网 时间:2024/06/05 00:24

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

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.


/* 整体思路: * 在反转链表的基础上,记录好左侧部分和右侧部分结点,然后和局部反转后的链表拼接起来即可 *//** * 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 == NULL || m < 1 || n < m)            return NULL;        ListNode* dummyHead = new ListNode(-1);        dummyHead->next = head;        ListNode* pCur = dummyHead;        ListNode* pPre = NULL;        ListNode* pNext = NULL;        // 让pCur指向m结点的前一个结点,存储为left        for (int i = 1; i <= m - 1; ++i)            pCur = pCur->next;        ListNode* left = pCur;        // pCur指向m结点        pCur = pCur->next;        // 反转部分的尾结点存储为right        ListNode* right = pCur;        // 对m到n位置的数进行反转        // 反转后这部分头结点为pPre        // 尾结点需要事先存储为right        // pNext为n右侧部分的头结点        // right -> pNext        // pPre接上m左侧部分 left->pPre        // pNext接上n右侧部分        for (int i = m; i <= n; ++i){            pNext = pCur->next;            pCur->next = pPre;            pPre = pCur;            pCur = pNext;        }        // left -> reverse part head: pPre -> ... -> reverse part tail:right ->pNext        left->next = pPre;        right->next = pNext;        return dummyHead->next;    }};

// 这样写应该会更清晰/** * 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) {        ListNode* dummyHead = new ListNode(-1);        dummyHead->next = head;        // 1.记录第m个节点的前驱,left存储        ListNode* pCur = dummyHead;        for(int i = 1; i < m; ++i)            pCur = pCur->next;        ListNode* left = pCur;        pCur = pCur->next;        ListNode* right = pCur;        // 2.翻转m --> n        ListNode* pPre = NULL;        ListNode* pNext = NULL;        for(int i = m; i <= n; ++i){            pNext = pCur->next;            pCur->next = pPre;            pPre = pCur;            pCur = pNext;        }        // 3.连接:left->pPre->...->right->pCur        left->next = pPre;        right->next = pCur;        return dummyHead->next;    }};