合并两个有序递增链表

题目如下:

 代码如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef struct ListNode {
 5     int val;
 6     struct ListNode *next;
 7 } ListNode_t;
 8 
 9 struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) 
10 {
11     struct ListNode* vhead;//新建一个头结点
12     struct ListNode *p = vhead;//用一个指针指向该头结点
13     while (pHead1 && pHead2)//两个链表都未比较完
14     {
15         if (pHead1->val <= pHead2->val) //表1的值更小
16         {
17             p->next = pHead1;    //先将结点连接到新表,再让原表指针后移一位,二者顺序不可换
18             pHead1 = pHead1->next;
19         }
20         else 
21         {
22             p->next = pHead2;
23             pHead2 = pHead2->next;
24         }
25         p = p->next;  //加入一个新结点后,新表指针也后移一位
26     }
27     p->next = pHead1 ? pHead1 : pHead2;  //都比较完后,哪个表非空则直接加入到新表中
28     return vhead->next;  //返回第一个结点
29 }
30 
31 int main()
32 {
33     // 链表1:1->20->95
34     ListNode_t * first_1;
35     ListNode_t * second_1;
36     ListNode_t * third_1;
37     first_1 = (ListNode_t*)malloc(sizeof(ListNode_t));
38     second_1 = (ListNode_t*)malloc(sizeof(ListNode_t));
39     third_1 = (ListNode_t*)malloc(sizeof(ListNode_t));
40     first_1->val = 1;
41     second_1->val = 20;
42     third_1->val = 95;
43     first_1->next = second_1;
44     second_1->next = third_1;
45     third_1->next = NULL;
46 
47     // 链表2:2->4->6
48     ListNode_t * first_2;
49     ListNode_t * second_2;
50     ListNode_t * third_2;
51     first_2 = (ListNode_t*)malloc(sizeof(ListNode_t));
52     second_2 = (ListNode_t*)malloc(sizeof(ListNode_t));
53     third_2 = (ListNode_t*)malloc(sizeof(ListNode_t));
54     first_2->val = 2;
55     second_2->val = 4;
56     third_2->val = 6;
57     first_2->next = second_2;
58     second_2->next = third_2;
59     third_2->next = NULL;
60 
61     ListNode_t* curr =  Merge(first_1,first_2);
62 
63     while(curr!=NULL)
64     {
65         printf("curr value = %d\n",curr->val);
66         curr = curr->next;
67     }
68 
69     return 0;
70 }

传入链表1: 1->20->95

传入链表2: 2->4->6

期望实验结果:1->2->4->6->20->95

验证结果如下:

 

posted @ 2024-06-02 09:35  昆山皮皮虾  阅读(17)  评论(0编辑  收藏  举报