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

Solution:
1->2->3->4->5->NULL
1->3->2->4->5->NULL
1->4->3->2->5->NULL     always insert the element after the (m-1)th element. 
Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode cur = head;
        ListNode pre = dummy;
        int pos = 1;
        
        while(pos < m && cur != null){
            pre = cur;
            cur = cur.next;
            pos++;
        }
        while(pos < n && cur != null){
            ListNode nt = cur.next.next;
            cur.next.next = pre.next;
            pre.next = cur.next;
            cur.next = nt;
            pos++;
        }
        return dummy.next;
    }
}

No comments:

Post a Comment