大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.6 KiB

  1. #include<iostream>
  2. using namespace std;
  3. struct ListNode
  4. {
  5. int val;
  6. ListNode* next;
  7. };
  8. struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
  9. // write code here
  10. if(pHead1 == NULL)return pHead2;
  11. if(pHead2 == NULL)return pHead1;
  12. struct ListNode* p1 = (pHead1->val <= pHead2->val ? pHead1 : pHead2);
  13. struct ListNode* p2 = (pHead1->val > pHead2->val ? pHead1 : pHead2);
  14. struct ListNode* p = p1; //p1是主链
  15. // temp存放中间指针,有可能在p1中有可能在p2中,最终每次指向p1链两个node之间和大node最近的那个点
  16. struct ListNode* temp =NULL;
  17. while((p1 != NULL)&&(p2 != NULL)){
  18. if(p1->val <= p2->val){
  19. temp = p1;
  20. p1 = p1->next;
  21. }
  22. else {
  23. temp->next = p2;
  24. temp = p2;
  25. p2 = p2->next;
  26. temp->next = p1;
  27. }
  28. }
  29. if(p1 == NULL){
  30. temp->next =p2;
  31. return p;
  32. }else return p;
  33. }
  34. int main(){
  35. ListNode* one = new ListNode;
  36. one->val = 1;
  37. ListNode* two = new ListNode;
  38. two->val = 3;
  39. ListNode* three = new ListNode;
  40. three->val = 4;
  41. ListNode* one2 = new ListNode;
  42. one2->val = 1;
  43. ListNode* two2 = new ListNode;
  44. two2->val = 2;
  45. ListNode* three2 = new ListNode;
  46. three2->val = 5;
  47. one->next = two;
  48. two->next = three;
  49. three->next = nullptr;
  50. one2->next = two2;
  51. two2->next = three2;
  52. three2->next = nullptr;
  53. ListNode* res = Merge(one, one2);
  54. ListNode* cur = res;
  55. cout << "init success" << endl;
  56. while(cur != nullptr){
  57. cout << cur->val << endl;
  58. cur = cur->next;
  59. }
  60. return 0;
  61. }