61. Rotate List

Description

Intuition

Pitfall


    // TODO: [section 1] Correct
    fast.next = dummy.next;
    dummy.next = slow.next;
    slow.next = null;

    // todo: [section 2] Incorrect when fast and slow on the same node.
   dummy.next = slow.next;
   fast.next = head;
   slow.next = null;

For example, if the list is dummy -> 1 -> null and k = 0, where slow and fast both point to dummy.

如果执行 section 2

  • 第一步后,dummy -> 1 -> null
  • 第二步后,dummy -> 1 -> null
  • 第三步后,dummy ->

容易挂在这两个case上

  @Test
  void testWith1And1() throws Exception {
    ListNode head = ListNodes.getListOfNodes(new int[]{1});
    ListNode expected = ListNodes.getListOfNodes(new int[]{1});
    assertEquals(expected, solution.rotateRight(head, 1));
  }

  @Test
  void testWith1And0() throws Exception {
    ListNode head = ListNodes.getListOfNodes(new int[]{1});
    ListNode expected = ListNodes.getListOfNodes(new int[]{1});
    assertEquals(expected, solution.rotateRight(head, 0));
  }

Solution

Solution

results matching ""

    No results matching ""