21. Merge Two Sorted Lists

来源:互联网 发布:投资公司的网络销售 编辑:程序博客网 时间:2024/05/29 19:43

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.
题目大意:合并两个有序链表,使得最后返回新的有序链表,并且这个新链表由这两个新链表的头结点组成

分析:大概的思路是归并算法
分别比较两个链表中的数,谁小谁到前面

/** * 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* newhead=new ListNode(-1);//新链表头结点        ListNode* temp=newhead;//临时头结点,代替newhead变换。因为newhead->next始终必须指向头结点。所以不能直接使用newhead去移动        while(l1&&l2)        {            if(l1->val<l2->val)            {                 temp->next=l1;                l1=l1->next;            }            else            {                temp->next=l2;                l2=l2->next;            }            temp=temp->next;//temp向后移        }        temp->next=l1?l1:l2;        return newhead->next;    }};