问题描述:
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;
}
}