92. 反转链表 IIhtml
把一个链表部分反转,这个是我常常爱出的面试题,今天终于轮到我作了面试
咱们在25. k个一组翻转链表中处理过相似的问题,那个更难,要求 k 个节点一组进行翻转。这个题相对起来就简单多了,咱们能够直接利用那个题的reverse函数.反转一下就能够了。函数
为了方便,咱们有个小trick,须要一个空的头节点指向第一个节点code
class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode trick = new ListNode(0); trick.next = head; ListNode p = trick; int k = 1; while (k < m) { p = p.next; k++; } reverse(p, n - m + 1); return trick.next; } // 反转front(不包括from)其后的k个节点 private ListNode reverse(ListNode front, int k) { ListNode from = front.next; if (from == null) return front;//相比较25题,这个须要多一个判断 ListNode head = from; ListNode cur = from.next; ListNode tmp = null; while (k > 1 && cur != null) { tmp = cur.next; cur.next = from; from = cur; cur = tmp; k--; } head.next = cur; front.next = from; return head; } }