LeetCode92. Reverse Linked List II(C++)

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

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

解题思路:双指针法,先遍历到m节点,再用头插法,将n-m个节点翻转

/**
 * 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 *p=new ListNode (0),*q=head,*pre;
        int cnt=n-m;
        p->next=head;head=p;
        for(int i=1;inext;
            q=q->next;
        }
        if(q->next==NULL)
            return head->next;
        pre=p->next;
        q=q->next;
        for(int i=0;inext=q->next;
            q->next=p->next;
            p->next=q;
            q=pre->next;
            if(q==NULL)
                break;
        }
        return head->next;
    }
};

 

你可能感兴趣的:(Leetcode)