1. 程式人生 > >合並兩個排序鏈表

合並兩個排序鏈表

算法 desc 有一個 合並 solution 我們 describe ext while

題目描述

輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。 思路:非遞歸
class Solution { 
  public: 
      ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 
      { 
          if(!pHead1) 
              return pHead2; 
          if(!pHead2) 
              return pHead1; 
          ListNode* Head; 
          ListNode* p; 
          //取較小值作頭結點 
          if(pHead1->val<=pHead2->val){ 
              Head=pHead1; 
              pHead1=pHead1->next; 
          } 
          else{ 
              Head=pHead2; 
              pHead2=pHead2->next; 
          }   
          //開始遍歷合並 
          p=Head;  //p為合並後的鏈表的工作指針 
          while(pHead1&&pHead2){    //當有一個鏈表到結尾時,循環結束 
              if(pHead1->val<=pHead2->val){         //如果鏈表1的結點小於鏈表2的結點 
                  p->next=pHead1;                  //取這個結點加入合並鏈表 
                  pHead1=pHead1->next;            //鏈表1後移一位 
                  p=p->next;                    //工作指針後移一位 
              }                
              else{                           //否則取鏈表2的結點

                  p->next=pHead2; 
                  pHead2=pHead2->next; 
                  p=p->next; 
              }                 
          } 
          if(pHead1 == NULL)           //鏈表1遍歷完了 
              p->next = pHead2;        //如果鏈表2也遍歷完了,則pHead2=NULL 
          if(pHead2 == NULL)            //鏈表2遍歷完了 
              p->next = pHead1;         ///如果鏈表1也遍歷完了,則pHead1=NULL

          return Head; 
      } 
  };

  

思路:遞歸算法。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(!pHead1) return pHead2;
        if(!pHead2)	return pHead1;
        if(pHead1->val <= pHead2->val) {
            pHead1->next= Merge(pHead1->next,pHead2);
            return pHead1;
        }
        else {
            pHead2->next = Merge(pHead1,pHead2->next);
            return pHead2;
        }
        
    }
};

  

https://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337

合並兩個排序鏈表