Leetcode ブラシ問題 (単一リンク リスト) 2 - 逆リンク リスト II

92. 逆リンクリストⅡ

リンクされたリストを位置 m から n に反転します。反転を完了するには 1 回のスイープを使用します。

/**
 * 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) {
    
    
        ListNode p = head;
        ListNode q = head;
        while(m > 2){
    
    
            --m;
            --n;
            p = p.next;
            q = q.next;
        }
        
        while(n > 1){
    
    
            --n;
            q = q.next;
        }
        if(m < 2){
    
    
            head = reverseList(p,q.next);
            return head;
        }
        //System.out.println("0: p : "+p.next.val+"; q : "+q.next.val);

        p.next = reverseList(p.next,q.next);
        return head;


    }
    public ListNode reverseList(ListNode head,ListNode end) {
    
    
        if(head == null)
            return head;
        ListNode next = head.next;
        head.next = end;
        while(next != end){
    
    
          
            ListNode next2 = next.next;
            next.next = head;
            head = next;
            next = next2;
        }
        //System.out.println("0: head : "+head.val);
        return head;
    }
}

おすすめ

転載: blog.csdn.net/qq_38754625/article/details/108521559