题目:
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、通常会用到的方法,新建一个头节点head,然后分别从两个链表中取出一个节点进行比较,然后依次插到head后,最后返回head.next;补充一下cpp中"."和"->"的区别:
c++中 . 和 -> 主要是用法上的不同。
1、A.B则A为对象或者结构体;
2、A->B则A为指针,->是成员提取,A->B是提取A中的成员B,A只能是指向类、结构、联合的指针;
例如:
class student
{
public:
string name[20];
}
第一种情况,采用指针访问 student *x,则访问时需要写成 *x.name="hello";等价于x->name="hello"。
第二种情况,采用普通成员访问 student x,则访问时需要写成 x.name="hello"。
2、递归,思路:当取到一个链表的节点为空的时候,返回另一条链表的节点;当取到的两个节点都不为空的时候,比较两个节点的大小,(从小到大排序)所以当l1的节点要是小于l2的节点时,说明此时l1的节点应该是在l2的节点的前边的,递归找下一个节点,依次这样;
递归的代码:
/**
* 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;
if(l1.val<l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}