将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路:利用归并排序的思想,循环遍历两个链表,如果遍历到的第一个链表的值小于第二个链表的值,那么将小的链表结点加入新的链表即可,反之如果比第二个链表的结点大,那么将第二个链表的结点加入新链表即可。直到遍历链表为空,将另外未遍历的结点加入新链表即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode newH = new ListNode(0);
ListNode firstNode = newH; //保存新链表的头结点,防止赋值时丢失。
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
newH.next = l1;
l1 = l1.next;
}else{
newH.next = l2;
l2 = l2.next;
}
newH = newH.next;
}
while(l1 != null){
newH.next = l1;
l1 = l1.next;
newH = newH.next;
}
while(l2 != null){
newH.next = l2;
l2 = l2.next;
newH = newH.next;
}
return firstNode.next;
}
}
大神代码:比较简洁,我还是欠考虑,忘记了考虑为空的情况下,就可直接返回了。简洁之处,将遍历到任意一条链表为空的时候,将后续代码的条件判断合并到了判断语句中。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)return l2;
if(l2==null)return l1;
ListNode listNode = new ListNode(0);
ListNode firstNode=listNode;
while(l1!=null||l2!=null){
if(l1!=null&&(l2==null||l1.val<=l2.val)){
listNode.next=l1;
l1=l1.next;
}else{
listNode.next=l2;
l2=l2.next;
}
listNode=listNode.next;
}
return firstNode.next;
}
}
c 语言:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode head;
struct ListNode *pre = &head;
while(l1 && l2){
if(l1->val <= l2->val){
pre->next = l1;
l1 = l1->next;
}else{
pre->next = l2;
l2 = l2->next;
}
pre = pre->next;
}
pre->next = (NULL == l1)?l2:l1;
return head.next;
}