LeetCode (Reverse Linked List II)

来源:互联网 发布:部落冲突更新软件 编辑:程序博客网 时间:2024/06/02 06:27

Problem:

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.

Solution:

/** * 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 l(0);        l.next = head;        ListNode *pre = &l, *cur;        for(int i = 0; i < m - 1; i++)            pre = pre->next;        cur = pre->next;        for(int i = 0; i < n - m; i++){            ListNode *move = cur->next;            cur->next = move->next;            move->next = pre->next;            pre->next = move;        }        return l.next;    }};