您的位置:首页 > 编程语言 > C语言/C++

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: