题目:
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.
说明:有序链表归并(从小到大)
1)此链表无头节点
实现:
方法一:非递归
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 12 ListNode *la=l1,*lb=l2; 13 ListNode *q=NULL,*p=NULL; 14 if(la==NULL) return l2; 15 if(lb==NULL) return l1; 16 //此单链表无头结点,若有头结点,可直接p=head节点即可,无需下面的if...else... 17 if((la->val) < (lb->val)) 18 { 19 p=la; 20 la=la->next; 21 } 22 else 23 { 24 p=lb; 25 lb=lb->next; 26 } 27 q=p; 28 while(la&&lb) 29 { 30 if((la->val) < (lb->val)) 31 { 32 p->next=la; 33 p=la; 34 la=la->next; 35 } 36 else 37 { 38 p->next=lb; 39 p=lb; 40 lb=lb->next; 41 } 42 } 43 p->next=la?la:lb; 44 return q; 45 } 46 };