国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

【面試題】劍指offer 17

2019-11-06 06:01:26
字體:
來源:轉載
供稿:網友

題目: 輸入兩個遞增的鏈表,合并兩個鏈表,并返回合并后的頭結點

#include<iostream>using namespace std;struct ListNode{ int _value; ListNode* pNext;};class MyList{public: MyList() :pHead(NULL) {} ~MyList() { delete pHead; pHead=NULL; } void addNode(const int value) { ListNode* newnode=new ListNode(); if (pHead==NULL) { newnode->_value=value; newnode->pNext=NULL; pHead=newnode; return; } ListNode* node=pHead; while(node->pNext!=NULL) { node=node->pNext; } newnode->_value=value; newnode->pNext=NULL; node->pNext=newnode; } ListNode* getHead() { return pHead; }PRivate: ListNode* pHead;};ListNode* MergeList(ListNode* pHead1,ListNode* pHead2){ if (pHead1==NULL) return pHead2; if(pHead2==NULL) return pHead1; ListNode* MerHead=NULL; if(pHead1->_value<pHead2->_value) { MerHead=pHead1; MerHead->pNext=MergeList(MerHead->pNext,pHead2); } else { MerHead=pHead2; MerHead->pNext=MergeList(MerHead->pNext,pHead1); } return MerHead;}void PrintList(ListNode* pHead){ ListNode* node=pHead; while (node) { cout<<node->_value<<" "; node=node->pNext; } cout<<endl;}void test(){ cout<<"test:"<<endl; MyList l1; l1.addNode(1); l1.addNode(3); l1.addNode(5); l1.addNode(7); l1.addNode(9); cout<<"l1:"; PrintList(l1.getHead()); MyList l2; l2.addNode(2); l2.addNode(4); l2.addNode(6); l2.addNode(8); l2.addNode(10); cout<<"l2:"; PrintList(l2.getHead()); ListNode* head=MergeList(l1.getHead(),l2.getHead()); cout<<"MergeList:"; PrintList(head);}void test2(){ cout<<"test2:"<<endl; MyList l1; l1.addNode(1); l1.addNode(3); l1.addNode(5); l1.addNode(7); l1.addNode(9); cout<<"l1:"; PrintList(l1.getHead()); MyList l2; cout<<"l2:"; PrintList(l2.getHead()); cout<<"MergeList:"; ListNode* head=MergeList(l1.getHead(),l2.getHead()); PrintList(head);}void test3(){ cout<<"test3:"<<endl; MyList l1; cout<<"l1:"; PrintList(l1.getHead()); MyList l2; cout<<"l2:"; PrintList(l2.getHead()); cout<<"MergeList:"; ListNode* head=MergeList(l1.getHead(),l2.getHead()); PrintList(head);}#include "List.h"#include<cstdlib>int main(){ test(); test2(); test3(); system("pause"); return 0;}

結果


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 额敏县| 阿勒泰市| 赤城县| 吐鲁番市| 马边| 迁安市| 咸丰县| 青海省| 循化| 临安市| 罗甸县| 禄丰县| 荣昌县| 襄樊市| 抚松县| 玉田县| 长葛市| 白山市| 光泽县| 宁陵县| 高陵县| 集安市| 霸州市| 兴化市| 桦川县| 南京市| 泰安市| 湘乡市| 肥城市| 磐石市| 抚顺市| 临武县| 涿州市| 织金县| 南乐县| 北碚区| 山丹县| 宣汉县| 高平市| 天镇县| 页游|