雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

C++實現(xiàn)合并兩個排序的鏈表

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊:

本文實例為大家分享了C++合并兩個排序的鏈表,供大家參考,具體內(nèi)容如下

問題描述

輸入兩個單調(diào)遞增的鏈表,輸出兩個鏈表合成后的鏈表,當然我們需要合成后的鏈表滿足單調(diào)不減規(guī)則。

struct ListNode {
  int val;
  struct ListNode *next;
  ListNode(int x) :
  val(x), next(NULL) {
  }
};

方法一

class Solution {
public:
  ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
  {
    ListNode* newList = NULL; //新鏈表頭
    ListNode* newListRear = NULL; //新鏈表尾
    // 先處理某個鏈表為空的情形
    if (pHead1 == NULL){
      return pHead2;
    }
    if (pHead2 == NULL){
      return pHead1;
    }
    // 把數(shù)值小的結(jié)點放入新鏈表,生成頭節(jié)點
    if (pHead1->val <= pHead2->val){
      newList = pHead1;
      newListRear = pHead1;
      pHead1 = pHead1->next;
    }else{
      newList = pHead2 ;
      newListRear = pHead2;
      pHead2 = pHead2->next;
    }
    // 兩表均不空的情形下,遍歷 
    while (pHead1 != NULL && pHead2 != NULL) {
      if (pHead1->val <= pHead2->val) {
        newListRear->next =pHead1;
        newListRear = pHead1;
        pHead1 = pHead1->next;
      }else{
        newListRear->next =pHead2;
        newListRear = pHead2;
        pHead2 = pHead2->next;
      }
    }
    //某一表為空時,把另一表接入新表表尾 
    if (pHead1 == NULL) {
      newListRear->next = pHead2;
    }
    if (pHead2 == NULL) {
      newListRear->next = pHead1;
    }
    
    return newList;
  }
};

方法二(遞歸思想)

class Solution {
public:
  ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
  {
    if (pHead1 == NULL){
      return pHead2;
    }
    if (pHead2 == NULL){
      return pHead1;
    }
    
    if (pHead1->val <= pHead2->val){ // pHead1為合并后的頭節(jié)點
      pHead1->next = Merge(pHead1->next, pHead2);
      return pHead1;
    }else{ // pHead2 為合并后的頭節(jié)點
      pHead2->next = Merge(pHead1, pHead2->next);
      return pHead2;
    }
  }
};

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。

上一篇:判斷兩顆二叉樹是否相似的兩種方法

欄    目:C語言

下一篇:C語言二維數(shù)組幾種常用的表示方法

本文標題:C++實現(xiàn)合并兩個排序的鏈表

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/409.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有