[LeetCode 92] Reverse Linked List II 翻转单链表II

 

/*
 * @Author: your name
 * @Date: 2019-12-24 10:12:25
 * @LastEditTime : 2019-12-24 11:57:33
 * @LastEditors  : Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \VScodeLeetCode\92.反转链表-ii.cpp
 */
/*
 * @lc app=leetcode.cn id=92 lang=cpp
 *
 * [92] 翻转单链表
 */

// @lc code=start
/**
 * 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(m==n) return head;
        ListNode* beginPtr;//指向待翻转子链前一个节点
        ListNode* w;//工作指针
        if(m==1)
        {            
            beginPtr = nullptr;
            w = head;
        }
        else
        {
            beginPtr = head;
            int i = m-1;
            while(--i)
            { 
                beginPtr = beginPtr->next;
            }
            w = beginPtr->next;
        }
        ListNode* subHead = w;//翻转前第m个节点
        ListNode* pre = nullptr;
        ListNode* post = nullptr;
        int subsize = n-m+1;//待翻转子链表长度
        while(subsize--)
        {
           post = w->next;
           w->next = pre;
           pre = w;
           w = post;
           if(beginPtr)
           {
               beginPtr->next = pre;
           } 
        }
        subHead->next = w;
        
        if(m==1) return pre;
        else return head;
    }
};
 


 

猜你喜欢

转载自www.cnblogs.com/wangxf2019/p/12090973.html