剑指office--------合并两个排序的链表
2021-04-11 02:27
标签:des public while lse val ice bsp 输入 style 剑指office--------合并两个排序的链表 标签:des public while lse val ice bsp 输入 style 原文地址:https://www.cnblogs.com/q1204675546/p/13362573.html题目描述
1 /*
2 struct ListNode {
3 int val;
4 struct ListNode *next;
5 ListNode(int x) :
6 val(x), next(NULL) {
7 }
8 };*/
9 class Solution {
10 public:
11 ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
12 {
13 if (pHead1==NULL&&pHead2==NULL) return NULL;
14
15 ListNode* node;
16 ListNode* Node;
17
18 if (pHead1!=NULL&&pHead2!=NULL){
19 if(pHead1->val val){
20 node=pHead1;
21 Node=node;
22 pHead1=pHead1->next;
23 }
24 else{
25 node=pHead2;
26 Node=node;
27 pHead2=pHead2->next;
28 }
29 }
30 else if (pHead1==NULL) return pHead2;
31 else if (pHead2==NULL) return pHead1;
32 while (pHead1!=NULL && pHead2!=NULL){
33 if (pHead1->val val){
34 node->next=pHead1;
35 node=node->next;
36 pHead1=pHead1->next;
37 }
38 else{
39 node->next=pHead2;
40 node=node->next;
41 pHead2=pHead2->next;
42 }
43 }
44 if (pHead1!=NULL){
45 node->next=pHead1;
46 }
47 else{
48 node->next=pHead2;
49 }
50 return Node;
51 }
52 };