leetcode 之Reverse Linked List II(15)

leetcode 之Reverse Linked List II(15)_第1张图片

这题用需要非常细心,用头插法移动需要考虑先移动哪个,只需三个指针即可。

ListNode *reverseList(ListNode *head, int m, int n)
      {
          ListNode dummy(-1);
          dummy.next = head;
          ListNode *prev = &dummy;

          for (int i = 0; i < m - 1; i++)
              prev = prev->next;//要调整的数之前的那个数

          ListNode *head2 = prev;
          prev = head2->next;
          ListNode *curr = prev->next;
          for (int i = m; i < n; i++)
          {
              prev->next = curr->next;//头插法
              curr->next = head2->next;
              head2->next = curr;

              curr = prev->next;
          }
      }
View Code

 

转载于:https://www.cnblogs.com/573177885qq/p/5505239.html

你可能感兴趣的:(leetcode 之Reverse Linked List II(15))