版权声明:转载请注明出处 https://blog.csdn.net/FGY_u/article/details/84349202
题目: https://leetcode.com/problems/merge-two-sorted-lists/
概述: 给定两个链表,让合并成一个链表,而且大小顺序要一定
思路: 遍历两个链表,谁值小,先插谁。
/**
* 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 *head = new ListNode(-1);
ListNode *cur = head;
while(l1 != NULL || l2 != NULL)
{
bool flag = (l1 != NULL ? (l1 -> val) : INT_MAX) < (l2 != NULL ? (l2 -> val) : INT_MAX) ? true : false;
if(flag)
{
cur -> next = new ListNode(l1 -> val);
cur = cur -> next;
l1 = l1 -> next;
}
else
{
cur -> next = new ListNode(l2 -> val);
cur = cur -> next;
l2 = l2 -> next;
}
}
return head -> next;
}
};