您的位置:首页 > 其它

Leetcode 92. Reverse Linked List II

2017-02-16 03:15 267 查看
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m >= n || head == null) {
return head;
}

// create a dummy node b/c m may be 1, thus we can't find node before reverse position
ListNode dummy = new ListNode(0);
dummy.next = head;

// find the node beofre the reverse position
ListNode left = dummy;
for (int i=1; i<m; i++) {
left = left.next;
}

// do the reverse for the list starting at left.next
ListNode prev = left.next;
ListNode curr = prev.next;
ListNode next = null;

// only change m-n links
for (int i=m; i<n; i++) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}

// link the head and tail
left.next.next = curr;
left.next = prev;

return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: