合并两个排序的链表

题目描述:

  输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

算法思想:

  这个题目的思想是通过两个指针分别指向两个链表,递归比较两个链表的值得大小,然后赋值给新建的头结点。直到结束。这里需要注意的就是,我们需要检查两个传进来的链表是否为空;

算法实现:

 1 #include<iostream>
 2 #include<stdlib.h>
 3 using namespace std;
 4 
 5 typedef struct ListNode{
 6     int data;
 7     struct ListNode *next;
 8 }ListNode;
 9 
10 ListNode * Merge(ListNode *pHead1, ListNode *pHead2){
11     if(pHead1 == NULL){                     //检查是否为空
12         return pHead2;
13     }
14     if(pHead2 == NULL){
15         return  pHead1;
16     }
17     
18     ListNode *pHead = NULL;
19     
20     if(pHead1->data < pHead2->data){           //递归合并两个链表
21         pHead = pHead1;
22         pHead->next = Merge(pHead1->next, pHead2);
23     }
24     else{
25         pHead = pHead2;
26         pHead->next = Merge(pHead1, pHead2->next);
27     }
28     
29     return pHead;
30 }
31 
32 ListNode *CreateList(int x){                              //创建链表
33     long num;
34     ListNode *pHead = NULL;
35     ListNode *p = NULL;
36       
37     while(x-- > 0){
38             cin>>num;  
39             ListNode* pNew = new ListNode();  
40             if(pNew == NULL){
41                     exit(EXIT_FAILURE);
42                 }
43             pNew->data = num;  
44             pNew->next = NULL;  
45          
46             if(pHead == NULL)  
47             {  
48                 pHead = pNew;  
49                 p = pHead;  
50             }  
51             else
52             {  
53                 p->next = pNew;  
54                 p = p->next;  
55             }   
56         }
57     return pHead; 
58 } 
59 
60 int main(){
61     int m, n;
62     
63     ListNode *p1 = NULL;
64     ListNode *p2 = NULL;
65     ListNode *result = NULL;
66     
67     while(cin>>m>>n){
68         p1 = CreateList(m);
69         p2 = CreateList(n);
70         result = Merge(p1, p2);
71         
72         if(result == NULL){
73             cout<<"NULL"<<endl;
74         }
75         else{
76             ListNode *index = result;
77             while(index != NULL){
78                 cout<<index->data<<' ';
79                 index = index->next;
80             }
81             cout<<endl;
82         }
83     }
84 }

参考数据:

《剑指offer》

posted @ 2016-03-29 15:43  Dormant  阅读(230)  评论(0编辑  收藏  举报