leetcode 之Reverse Nodes in k-Group(22)

这题有点繁琐,在更新指针时很容易出错。

ListNode *reverseKGroup(ListNode *head, int k)
      {
          if (head == nullptr || head->next == nullptr || k < 2)return head;

          ListNode dummy(-1);
          dummy.next = head;

          for (ListNode *prev = &dummy, *end = head; end; end = prev->next)
          {
              for (int i = 1; i < k; i++)
                  end = end->next;
              if (end == nullptr)break;

              prev = reverse(prev, prev->next, end);

          }

          return dummy.next;
      }

      ListNode *reverse(ListNode *prev, ListNode *begin, ListNode *end)
      {
          ListNode *end_next = end->next;
          for (ListNode *p = begin, *cur = p->next, *pnext = cur->next; cur != end_next;
              p = cur, cur = pnext, pnext =cur? pnext->next:nullptr)
          {
              cur->next = p;//注意指针的指向是一个一个的改变的
          }
          begin->next = end_next;
          prev->next = end;
          return begin;
      }
View Code

 

posted @ 2016-05-19 15:52  牧马人夏峥  阅读(155)  评论(0编辑  收藏  举报