Leetcode92. Reverse Linked List II

反转链表的题没啥难的,就是多弄几个指针,别断链丢节点就行。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null) return null;
        
        ListNode dummy = new ListNode(-1);
        dummy.next=head;
        ListNode pre = dummy;
        ListNode phead = head;
        ListNode ptail = head.next;
        for(int i=1;i<m;i++){
            pre = pre.next;
            phead = phead.next;
            ptail = ptail.next;
        }
        for(int i=0;i<n-m;i++){
            ListNode temp = ptail.next;
            ptail.next = phead;
            
            phead = ptail;
            ptail = temp;
        }
        pre.next.next = ptail;
        pre.next = phead;
        return dummy.next;
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List II.
Memory Usage: 35.8 MB, less than 92.53% of Java online submissions for Reverse Linked List II.

posted @ 2019-04-23 16:22  大胖子球花  阅读(53)  评论(0)    收藏  举报