(一)题目描述
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
(二)算法描述
1 先创建一个头结点,用来合并两个有序链表
2 声明一个节点的引用指向头结点,用于返回头结点信息,进行访问输出
3 分为节点信息两个都不为空和有一个为空的情况进行编码
(三)LeetCode AC代码
/** * 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 temp = new ListNode(0); //生明一个引用保存头结点信息 ListNode save = temp; while(l1 != null && l2 != null){ if(l1.val < l2.val){ temp.next = l1; l1 = l1.next; temp = temp.next; }else{ temp.next = l2; l2 = l2.next; temp = temp.next; } } if(l1 == null){ temp.next = l2; } if(l2 == null){ temp.next = l1; } return save.next; } }
祝明天好运,加油自己!!