Merge Two Sorted Lists--LeetCode

àì夳堔傛蜴生んèń 2022-08-07 13:40 113阅读 0赞

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

  1. /*
  2. 始终将second链表节点插入到first链表中
  3. */
  4. List* Merge_list(List* first,List* second)
  5. {
  6. List* result = first;
  7. List* pre;
  8. if(first->value > second->value)
  9. {
  10. pre = first;
  11. first = second;
  12. second = pre;
  13. }
  14. //始终将second链表中的节点插入到first链表中
  15. while(first->next!=NULL && second != NULL)
  16. {
  17. if(first->next->value > second->value)
  18. {
  19. pre = second->next;
  20. second->next = first->next;
  21. first->next = second;
  22. second = pre;
  23. }
  24. else
  25. first = first->next;
  26. }
  27. if(second != NULL)
  28. {
  29. first->next=second;
  30. }
  31. return result;
  32. }

思路:还有一种方法,就是使用一个新的节点将两个链表进行连接。借助一个新的节点。

  1. List* MergeList(List* first,List* second)
  2. {
  3. List* head = new List;
  4. List* cur;
  5. head->next = NULL;
  6. cur = head;
  7. while(first != NULL && second !=NULL)
  8. {
  9. if(first->value <second->value)
  10. {
  11. cur->next = first;
  12. first = first->next;
  13. }
  14. else
  15. {
  16. cur->next = second;
  17. second = second->next;
  18. }
  19. cur = cur->next;
  20. }
  21. if(first == NULL)
  22. cur->next = second;
  23. else
  24. cur->next = first;
  25. return head->next;
  26. }

发表评论

表情:
评论列表 (有 0 条评论,113人围观)

还没有评论,来说两句吧...

相关阅读