合并两个排序的链表
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tqId=11169&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
非递归
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode *head=NULL; if(pHead1==NULL) return pHead2; else if(pHead2==NULL) return pHead1; ListNode *p; while(pHead1!=NULL&&pHead2!=NULL) { if(pHead1->val>pHead2->val) { if(head==NULL) p=head=pHead2; else{ p->next=pHead2; p=p->next; } pHead2=pHead2->next; } else{ if(head==NULL) p=head=pHead1; else { p->next=pHead1; p=p->next; } pHead1=pHead1->next; } } if(pHead1!=NULL) p->next=pHead1; if(pHead2!=NULL) p->next=pHead2; return head; } };
递归形式
非递归形式类似于归并排序两个数组
主要是新链表第一个头节点的处理
比较之后先判断一下新链表头节点有没有赋值,没有的话先赋值,并将p指向新链表最后一个结点
否则让p指向两个链表中大的那一个
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode *head=NULL; if(pHead1==NULL) return pHead2; else if(pHead2==NULL) return pHead1; if(pHead1->val>pHead2->val) { head=pHead2; head->next=Merge(pHead1,pHead2->next); } else{ head=pHead1; head->next=Merge(pHead1->next,pHead2); } return head; } };
递归形式很好理解,每次都返回两个列表中大的那个结点;