LeetCode | Reverse Linked List II

题目:

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->NULLm = 2 and n = 4,

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

Note:
Given mn 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode* p = new ListNode(0);
        p->next = head;
        
        ListNode* begin = p;
        
        int tmp = m - 1;
        while(tmp > 0)
        {
            p = p->next;
            tmp--;
        };
        
        ListNode * cur = p->next;
        p->next = NULL;
        
        tmp = n - m + 1;
        while(tmp-- > 0)
        {
            ListNode * t = cur->next;
            cur->next = p->next;
            p->next = cur;
            
            cur = t;
        };
        
        while(p->next != NULL)
        {
            p = p->next;
        };
        
        if(cur != NULL)
        {
            p->next = cur;
        };
        
        begin = begin->next;
        
        return begin;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11713389
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞