leetcode_c++:链表:Merge Two Sorted Lists(021)
来源:互联网 发布:淘宝童装名字大全 编辑:程序博客网 时间:2024/05/16 15:26
题目
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;}
0 0
- leetcode_c++:链表:Merge Two Sorted Lists(021)
- 021 - Merge Two Sorted Lists
- 021 Merge Two Sorted Lists
- 021 Merge Two Sorted Lists
- 021Merge Two Sorted Lists
- 【链表】Merge Two Sorted Lists
- 链表 Merge Two Sorted Lists
- leetcode_c++:链表:Merge k Sorted Lists(023)
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- 线程泄露问题解决(参考)
- 常用算法集合
- 版本控制
- Android export jar file和代码混淆。
- JAVA三大特性--多态
- leetcode_c++:链表:Merge Two Sorted Lists(021)
- 今天突然ubuntu下的virtual box出问题了
- Retrofit和okhttp的了解和使用
- 修路
- Android C#开发--The file "obj\Debug\android\bin\packaged_resources" does not exist.
- [JZOJ4628] 立方体
- IOS代理
- 实例 -- Loadrunner实现Android / IOS 手机APP压力测试
- 剑指offer之二进制中的1的个数与斐波那契数列