leetcode_c++:链表:Merge Two Sorted Lists(021)
2016-07-15 16:12
435 查看
题目
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.算法
O(n)#include <iostream> #include <vector> #include<cmath> using namespace std; struct ListNode{ int val; ListNode* next; ListNode(int x):val(x),next(NULL){} }; int ListInsert(ListNode* L, int pos,int data){ int j=1; ListNode *p,*s; p=L; while(p && j<pos){ p=p->next; ++j; } if(!p||j>pos) return 0; s=new ListNode(0); s->val=data; s->next=p->next; p->next=s; return 1; } // 打印 int ListTraverse(ListNode* L){ ListNode *p=L->next; while(p){ cout<<p->val<<endl; p=p->next; } printf("\n"); return 1; } //leetcode------------------- class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode *start, *cur; if (l1->val < l2->val) { cur = start = l1; l1 = l1->next; } else { cur = start = l2; l2 = l2->next; } while (l1 != NULL && l2 != NULL) { if (l1->val < l2->val) { cur->next = l1; cur = l1; l1 = l1->next; } else { cur->next = l2; cur = l2; l2 = l2->next; } } if (l1 != NULL) cur->next = l1; else cur->next = l2; return start; } }; //------------- int main(){ ListNode *l1,*l2,*ll1,*ll2; int n1,n2; Solution s; cin >>n1; ll1=l1=new ListNode(0); for(int i=0;i<n1;i++){ //无头节点 l1->next=new ListNode(0); l1=l1->next; cin>>l1->val; //cout<<endl; } ListTraverse(ll1); cin >>n2; ll2=l2=new ListNode(0); for(int i=0;i<n2;i++){ //无头节点 l2->next=new ListNode(0); l2=l2->next; cin>>l2->val; // cout<<endl; } ListTraverse(ll2); ListNode *res=s.mergeTwoLists(ll1->next,ll2->next); while(res!=NULL){ cout<<res->val<<' '; res=res->next; } return 0; }
相关文章推荐
- C++11带来的优雅语法
- C++ 共享内存 函数封装
- 关于C++中的虚拟继承的一些总结
- 了解C++资源库提高C++开发效率
- C++ PP Chapter Ⅴ 循环 and Chapter Ⅵ 分支
- leetcode344题 题解 翻译 C语言版 Python版
- Refactor: replace type code with class (c++)
- handle句柄
- C语言中的static 详细分析
- c++ : new 在特定指针处构造初始化
- cpp代码注释
- c++动态加载
- C/C++ 笔试、面试题目大汇总
- 常见排序算法C++总结
- 用程序解密爱因斯坦经典难题(C++)
- c++11新特性
- 《深度探索C++对象模型》1
- 1028. 人口普查(20)
- C++高级编程(成为C++高手的必由之路)
- 设计模式之外观模式(Facade)C++