[LeedCode OJ]#21 Merge Two Sorted Lists

来源:互联网 发布:巨人网络总裁 编辑:程序博客网 时间:2024/06/17 06:54

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:libin493073668@sina.com】


题目链接: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 *l3 = new ListNode(0);ListNode *newlist = l3;while(l1&&l2){if(l1->val<=l2->val){l3->next = l1;l1 = l1->next;}else{l3->next = l2;l2 = l2->next;}l3 = l3->next;}l3->next = l1?l1:l2;return newlist->next;}};


0 1