LeetCode92-反转链表 II(C++实现)

1.题目描述

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

 

2.代码实现

/**
 * 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 == nullptr || m == n)
            return head;
        
        if(m == 1)
        {
            int cnt = 0;
            ListNode* myhead = new ListNode(-1);
            myhead->next = head;
            ListNode* cur = head;
            while(cnt < (n - m) && cur->next)
            {
                ListNode *t = cur->next;
                cur->next = t->next;
                t->next = myhead->next;
                myhead->next = t;
                cnt++;
            }
            head = myhead->next;
            delete myhead;
        }
        else
        {
            ListNode* pre = head;
            for(int i = 1; i < m-1; i++)
                pre = pre->next;
            
            ListNode* cur = pre->next;
            for(int i = m; i < n; i++)
            {
                ListNode *t = cur->next;
                cur->next = t->next;
                t->next = pre->next;
                pre->next = t;              
            }
        }
        return head;
    }
};

 


版权声明:本文为starzyh原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。