Wednesday, July 23, 2014

Reverse Linked List II

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->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤ length of list.

链表部分反转,找到开始反转的位置,反转 n - m次。
public class Solution {
    //Time: O(n)
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        
        for (int i = 0; i < m - 1; i++) {
            head = head.next;
        }
        int num = 0;
        ListNode pre = head;
        head = head.next;
        while (num < n - m) {
            ListNode tmp = head.next;
            head.next = tmp.next;
            tmp.next = pre.next;
            pre.next = tmp;
            num++;
        }
        return dummy.next;
    }
}

No comments:

Post a Comment