LeetCode:Reverse Linked List II

Reverse Linked List II


Total Accepted: 68264  Total Submissions: 246589  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Linked List
Hide Similar Problems
  (E) Reverse Linked List


























code:

/**
 * 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;
        n-=m;
        ListNode dummy(0);
        dummy.next = head;
        
        ListNode *pre = &dummy;
        while(--m) pre = pre->next;
        ListNode *p = pre->next;
        
        while(n--){
            ListNode *tmp = p->next;
            p->next = tmp->next;
            tmp->next = pre->next;
            pre->next = tmp;
        }
        return dummy.next;
    }
};



你可能感兴趣的:(LeetCode,list,reverse,linked)