LeetCode021 Merge Two Sorted Listss C语言

简介:
1
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

题意:合并两个有序单链表,合并后的仍然是有序的。。。。。。。。。。。。。。。。。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
  * Definition for singly-linked list.
  * struct ListNode {
  *     int val;
  *     struct ListNode *next;
  * };
  */
struct  ListNode* mergeTwoLists( struct  ListNode* l1,  struct  ListNode* l2) {
     //首先判断有没有空链表的情况。。。。。
     if (l1 && !l2)
     return  l1;
     if (!l1 && l2)
     return  l2;
     if (!l1 && !l2)
     return  NULL;
     //还是和之前的002题要保存新链表头,中间节点head负责遍历
     struct  ListNode* head;
     struct  ListNode* ret;
     //找到新链表的头
     if (l1->val<l2->val){
         head=l1;
         l1=l1->next;
     } else {
         head=l2;
         l2=l2->next;
     }
     ret=head;
     //负责遍历。哪个小就指向哪个,直到有一个遍历完
     while (l1&&l2){
         if (l1->val<l2->val){
             head->next=l1;
             l1=l1->next;
         } else {
             head->next=l2;
             l2=l2->next;
         }
         head=head->next;
     }
     //遍历完后看看谁还剩下直接指向剩下的部分
     if (l1){
         head->next=l1;
     }
     if (l2){
         head->next=l2;
     }
     return  ret;
     }

。。。。。。。。。。。。。。。。太笨了。。。。。。。。。。。。。。。。继续练习吧少年。。。。。。。。。。。。。。。


本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1864639


相关文章
|
算法 C语言 容器
从C语言到C++_18(stack和queue的常用函数+相关练习)力扣(上)
从C语言到C++_18(stack和queue的常用函数+相关练习)力扣
97 0
|
存储 C语言
Leetcode—— 删除排序数组中的重复项——C语言
Leetcode—— 删除排序数组中的重复项——C语言
|
算法 C语言
Leetcode----旋转数组 ------C语言篇
Leetcode----旋转数组 ------C语言篇
105 0
|
C语言
LeetCode---消失的数字---C语言实现
LeetCode---消失的数字---C语言实现
|
算法 C语言 容器
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145(下)
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145
101 7
|
存储 算法 C语言
从C语言到C++_39(C++笔试面试题)next_permutation刷力扣
从C语言到C++_39(C++笔试面试题)next_permutation刷力扣
166 5
|
存储 C语言 容器
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(下)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
106 1
|
存储 C语言 容器
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(中)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
103 1
|
存储 自然语言处理 C语言
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别(上)
从C语言到C++_26(set+map+multiset+multimap)力扣692+349+牛客_单词识别
136 1
|
C语言
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145(中)
从C语言到C++_25(树的十道OJ题)力扣:606+102+107+236+426+105+106+144+94+145
107 1