Merge Two Sorted Lists
题目描述:
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
(输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。)
思路:
一、用循环来做:这道题目比较简单,考察链表的基本用法,从头到尾分别扫描两个链表,比较元素大小,小的元素即插入新的链表中。注意特殊值的判断,如果两个链表中有一个为空,则直接返回另一个链表即可。
二、用递归来做:
分析两个链表合并的过程,从合并两个链表的头结点开始,新的链表的头结点是原来两个链表中值较小的头结点;继续合并剩余的结点,在剩余的两个链表中剩下的结点依然是排序的,我们还是比较两个头结点的值,我们将值较小的头结点的值和前面合并得到的链表的尾结点链接起来,依次类推,这是典型的递归问题。
注意鲁棒性问题,要对空链表做特殊处理。
解决:
/**
*思路一,循环实现合并排序链表
* 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 list =new ListNode(0);//头引用,创建头结点
ListNode p = list;//临时引用(指针)
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
p.next = l1;
l1 = l1.next;
}
else{
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if( l2 != null){
p.next = l2;
}
if(l1 != null){
p.next = l1;
}
return list.next;//因为头结点的元素不是要求的两个链表中的元素,故从list.next开始返回
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1==null)
return list2;
if(list2==null)
return list1;
//思路二,递归实现合并排序链表
ListNode mergeHead = null;
if(list1.val<list2.val){
mergeHead=list1;
mergeHead.next=Merge(list1.next,list2);
}
else{
mergeHead=list2;
mergeHead.next=Merge(list1,list2.next);
}
return mergeHead;
}
}
————————————————
版权声明:本文为CSDN博主「my_learning_road」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/my_learning_road/article/details/79471385