题解 | #链表内指定区间反转#

链表内指定区间反转

http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

区间分为[...]->[prev]->[h]->[...]->[t]->[tail]->[...]
要反转的是h和t之间的节点(包括h和t)

// 反转区间[head, tail]
pair<ListNode*, ListNode*> reverseList(ListNode* head, ListNode* tail) {
  ListNode* p = nullptr;
  ListNode* q = head;
  ListNode* r = nullptr;
  ListNode* end = tail->next;
  while (q != end) {
    r = q->next;
    q->next = p;
    p = q;
    q = r;
  }
  return make_pair(tail, head);
}

ListNode* reverseBetween(ListNode* head, int m, int n) {
  if (head == nullptr || m == n) return head;
  auto dummy = new ListNode(-1);
  dummy->next = head;
  auto prev = dummy;
  for (int i = 1; i < m; ++i) {
    prev = prev->next;
  }
  auto t = prev->next;
  for (int i = m; i < n; ++i) {
    t = t->next;
  }
  auto h = prev->next;
  prev->next = nullptr;
  auto next = t->next;
  t->next = nullptr;
  auto pr = reverseList(h, t);
  prev->next = pr.first;
  pr.second->next = next;
  return dummy->next;
}

ListNode* CreateList(vector<int>& vec) {
  auto dummy = new ListNode(0);
  auto p = dummy;
  for (auto v : vec) {
    auto node = new ListNode(v);
    p->next = node;
    p = p->next;
  }
  return dummy->next;
}

int main() {
  vector<int> vec{ 1,2,3,4,5 };
  auto head = CreateList(vec);
  auto ans = reverseBetween(head, 2, 4);
  return 0;
}
全部评论

相关推荐

dongsheng66:如果想进大厂的话,在校经历没必要占这么大篇幅,可以把专业技能单独放一个专栏写,可以加个项目经历
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务