輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,固然咱們須要合成後的鏈表知足單調不減規則。node
遞歸spa
class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode* node=NULL; if(pHead1==NULL) { return node=pHead2; } if(pHead2==NULL) { return node=pHead1; } if(pHead1->val>pHead2->val){ node=pHead2; node->next=Merge(pHead1,pHead2->next); }else{ node=pHead1; node->next=Merge(pHead1->next,pHead2); } return node; } };
非遞歸code
public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { //新建一個頭節點,用來存合併的鏈表。 ListNode head=new ListNode(-1); head.next=null; ListNode root=head; while(list1!=null&&list2!=null){ if(list1.val<list2.val){ head.next=list1; head=list1; list1=list1.next; }else{ head.next=list2; head=list2; list2=list2.next; } } //把未結束的鏈表鏈接到合併後的鏈表尾部 if(list1!=null){ head.next=list1; } if(list2!=null){ head.next=list2; } return root.next; } }