#include "iostream"
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
void print(ListNode *head)
{
ListNode *p = head;
while (p != NULL)
{
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
// l1: 2
// l2: 1
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if (l1 == NULL)
{
return l2;
}
else if (l2 == NULL)
{
return l1;
}
ListNode *p1, *p2, *s;
if (l1->val <= l2->val)
{
p1 = l1;
p2 = l2;
}
else
{
p1 = l2;
p2 = l1;
l1 = l2;
}
while (p2 != NULL)
{
if(p1->next==NULL)
{
p1->next = p2;
}
if (p1->next->val < p2->val)
{
p1 = p1->next;
}
else
{
s = p2->next;
p2->next = p1->next;
p1->next = p2;
p2 = s;
}
}
return l1;
}
};
int main(int argc, char const *argv[])
{
ListNode *l1, *l2, *p;
int x;
Solution so;
cout << "input l1:" << endl;
cin >> x;
p = new ListNode(x);
l1 = p;
while (true)
{
cin >> x;
p->next = new ListNode(x);
p = p->next;
if (cin.get() == '\n')
break;
}
cout << "input l2:" << endl;
cin >> x;
p = new ListNode(x);
l2 = p;
while (true)
{
cin >> x;
p->next = new ListNode(x);
p = p->next;
if (cin.get() == '\n')
break;
}
so.mergeTwoLists(l1, l2);
so.print(l1);
return 0;
}
【Leetcode】21.合并两个有序链表C++
猜你喜欢
转载自blog.csdn.net/weixin_44936889/article/details/104086076
今日推荐
周排行