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.

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; }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
    	if (head==null || head.next==null) {
        	return head;
        }
    	ListNode tmp = new ListNode(-1);
    	tmp.next = head;
    	ListNode pre = tmp;
        ListNode node1 = null;
        ListNode node2 = null;
    	for (int i = 0; i < n; i++) {
    		if (i < m-1) {
    			pre = pre.next;
    		} else if (i == m-1) {
    			node1 = pre.next;
    			node2 = node1.next;
    		} else {
    			node1.next = node2.next;
    			node2.next = pre.next;
    			pre.next = node2;
    			node2 = node1.next;
    		}
    	}
    	return tmp.next;
    }
}

 

你可能感兴趣的:(list)