反转从位置 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; } }
标签:pre,count,leftNode,ListNode,反转,扫描,next,链表,null 来源: https://www.cnblogs.com/q-1993/p/11144074.html