您的位置:首页 > 其它

Leetcode 之 Merge Two Sorted Lists

2016-12-24 17:47 295 查看
问题描述:

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.

涉及到指针不断变换的题目还是用递归的方法最简单

代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode headA, ListNode headB) {
if(headA==null)
return headB;
if(headB==null)
return headA;
ListNode head;
ListNode res;
if(headA.val>headB.val){
head=headB;
res=mergeTwoLists(head.next,headA);
}
else{
head=headA;
res=mergeTwoLists(head.next,headB);
}
head.next=res;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 递归