16 合并两个排序的链表

 1 合并两个排序的链表
 2 //输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 3 struct ListNode 
 4 {
 5     int val;
 6     struct ListNode *next;
 7     ListNode(int x) :val(x), next(NULL)
 8     {
 9     }
10 };
11 //------------------递归做法------------
12 //注意递归的时候,备份节点然后进行使用以及返回,
13 //但是转为循环的时候,必须将遍历的节点进行备份,然后返回源节点
14 class Solution 
15 {
16 public:
17     ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
18     {
19         if (pHead1 == NULL)
20         {
21             return pHead2;
22         }
23         if (pHead2 == NULL)
24         {
25             return pHead1;
26         }
27         //遍历链表
28         ListNode* pMergerHead = NULL;
29         ListNode* pList1 = pHead1;
30         ListNode* PList2 = pHead2;
31            if (pList1->val <PList2->val)
32            {
33                pMergerHead = pList1;
34                pMergerHead->next = Merge(pList1->next, PList2);
35            }
36            else
37            {
38                pMergerHead = PList2;
39                pMergerHead->next = Merge(pList1, PList2->next);
40            }
41            return pMergerHead;
42     }
43 };
44 
45 //思路:分别用两个链表的头结点进行进行遍历,小的放在前,大的放在后面
46 class Solution {
47 public:
48     ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
49     {
50         if(!pHead1)
51             return pHead2;
52         if(!pHead2)
53             return pHead1;
54         ListNode* Head;
55         ListNode* p;
56         //取较小值作头结点
57         if(pHead1->val<=pHead2->val)
58         {
59             Head=pHead1;
60             pHead1=pHead1->next;
61         }
62         else
63         {
64             Head=pHead2;
65             pHead2=pHead2->next;
66         }  
67         //开始遍历合并
68         p=Head;                                                   
69         while(pHead1&&pHead2)
70         {                      
71             if(pHead1->val<=pHead2->val)
72             {          
73                 p->next=pHead1;                            
74                 pHead1=pHead1->next;                 
75                 p=p->next;                                     
76             }               
77             else
78             {                                               
79                 p->next=pHead2;
80                 pHead2=pHead2->next;
81                 p=p->next;
82             }                
83         }
84         if(pHead1 == NULL)           
85             p->next = pHead2;        
86         if(pHead2 == NULL)           
87             p->next = pHead1;        
88         return Head;
89     }
90 };

 

posted @ 2017-08-20 22:16  繁星的夜空2012  阅读(93)  评论(0编辑  收藏  举报