LeetCode 92. Reverse Linked List II

Posted Shendu.cc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 92. Reverse Linked List II相关的知识,希望对你有一定的参考价值。

题目

/**
 * 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)
            return head;
        
        ListNode * term = head;
        
        int pos=1;
        int tag=1;
        
        ListNode * temp;
        ListNode * pre = head;
        ListNode * temp2 = temp;
        ListNode * term2;
        
        while(term!=NULL)
        {
          
            if(pos>=m&&pos<=n)
            {
                if(tag==1)
                {
                    temp = term;
                    term = term->next;
                    pos++;
                    
                    temp->next=NULL;
                    term2 = temp;
                    tag=2;
                    continue;
                }
                else
                {
                    ListNode * term3 = term;
                    term = term->next;
                    term3->next = term2;
                
                    term2 = term3;
                    pos++;
                    continue;
                }
            }
            else
            {
                if(tag==2)
                {
                  
                    break;
                }
            }
            
            if(tag==1)
            {
                pre = term; 
            } 
            
            term = term->next;
            pos++;
        }
        temp->next = term;
        if(m!=1)
             pre->next = term2;
        
        if(m==1)
            return term2;
        else
            return head;
        
    }
};

以上是关于LeetCode 92. Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode92]Reverse Linked List II

#Leetcode# 92. Reverse Linked List II

Leetcode 92. Reverse Linked List II

leetcode.92. Reverse Linked List II

[LeetCode]92. Reverse Linked List II

LeetCode 92. Reverse Linked List II