Leetcode 92. Reverse Linked List II

来源:互联网 发布:如何优化网页加载速度 编辑:程序博客网 时间:2024/06/05 23:43
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;    }}

0 0
原创粉丝点击