編程演算法之合并有序鏈表

來源:互聯網
上載者:User

題目:

合并有序鏈表, 給定兩個升序的鏈表, 返回一個合并之後的升序鏈表.

節點結構:

struct Node{

int val;

Node *next;

};

要求實現的函數:

Node* mergeList(Node *list_a, Node* list_b)

代碼:

/*  * test.cpp  *  *  Created on: 2014.04.24  *      Author: Spike  */      /*eclipse cdt, gcc 4.8.1*/      #include <iostream>  #include <vector>        using namespace std;        struct Node{      int val;      Node *next;  };        Node* mergeList(Node *list_a, Node* list_b) {      if (list_a == NULL) //遞迴的終止條件          return list_b;      else if (list_b == NULL)          return list_a;            Node* pMergedHead = NULL; //合并後的鏈表            if (list_a->val < list_b->val) {          pMergedHead = list_a; //指向頭結點          pMergedHead->next = mergeList(list_a->next, list_b); //遞迴      } else {          pMergedHead = list_b;          pMergedHead->next = mergeList(list_a, list_b->next);      }            return pMergedHead;  }        Node* initList(const std::vector<int>& vi) {      Node* pHead = new Node;      Node* pTemp = pHead;            for (std::size_t i=0; i<vi.size(); ++i) {          pTemp->val = vi[i];                if (i != vi.size()-1) { //非尾結點              Node* pNode = new Node;              pTemp->next = pNode;              pTemp = pTemp->next;          }      }            pTemp->next = NULL;            return pHead;  }        void printList(Node* L) {      Node* pTemp = L;      while (pTemp->next != NULL) {          std::cout << pTemp->val << " ";          pTemp = pTemp->next;      }      std::cout << pTemp->val << " "; //列印最後一個值      std::cout << std::endl;  }        int main(void) {      std::vector<int> via = {1, 2, 3, 4, 5, 13};      std::vector<int> vib = {2, 4, 5, 7, 9, 11};            Node* list_a = initList(via);      Node* list_b = initList(vib);      std::cout << "list_a = "; printList(list_a);      std::cout << "list_b = "; printList(list_b);            Node* list_merge = mergeList(list_a, list_b);      std::cout << "list_merge = "; printList(list_merge);            return 0;  }

輸出:

list_a = 1 2 3 4 5 13   list_b = 2 4 5 7 9 11   list_merge = 1 2 2 3 4 4 5 5 7 9 11 13

返回欄目頁:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/

作者:csdn部落格 Caroline-Wendy

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.