【剑指offer】【链表】25.合并两个排序的链表
题目链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
遍历
当两个链表都不为空时,遍历两个链表,依次比较两个节点的值,将较小的节点的插入到新链表后面;
最后检查一下哪个链表还没有遍历完,直接将该链表的后续节点都接到新链表后面,返回新链表的头结点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* p = new ListNode(-1);
ListNode* ret = p;
while(l1 && l2){
if(l1 -> val <= l2 -> val){
p -> next = l1;
l1 = l1 -> next;
}
else{
p -> next = l2;
l2 = l2 -> next;
}
p = p -> next;
}
p -> next = l1 ? l1 : l2;
return ret -> next;
}
};
知识的价值不在于占有,而在于使用