leetcode 之Reverse Linked List II(15)

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

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

 

posted @ 2016-05-18 14:45  牧马人夏峥  阅读(96)  评论(0编辑  收藏  举报