反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

/**
 * 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 || head.next == null) {
            return head;
        }
        ListNode newHead = new ListNode(0);
        newHead.next = head;
        ListNode pre = newHead;
        int count = 1;
        while (pre !=  null && count != m) {
            pre = pre.next;
            count++;
        }
        ListNode leftNode = pre.next;
        pre.next = null;
        ListNode temp=null;
        count--;
        while(leftNode!=null && count < n) {
            count++;
            temp = leftNode;
            leftNode = leftNode.next;
            temp.next = pre.next;
            pre.next = temp;
        }
       while(pre.next!=null) {
          pre = pre.next; 
       }
        pre.next = leftNode;
        return newHead.next;
        
    }    
}

 

上一篇:用c++实现自定义红黑树(带有插入功能,左旋转,右旋转)


下一篇:glance 迁移