题目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。例如输入图3.7中的链表1和链表2,则合并之后的升序链表如链表3所示。链表结点定义如下:
typedef struct list
{
struct list* _next;
int _val;
}list;
思路一:
可以把两个链表的元素都放到一个数组里,将数组排序,在把所有的元素重新创建一个新链表,
这种方法容易想到,但是复杂度太高!
思路二:
直接合并两个链表,新建一个新的头节点,开始比较两个链表中的节点的值,值小的节点插入到后边,知道有一条链表走到末尾,再将没走完的链表插入到后边!
开始实现:
尾插和打印函数:
void push_back(list* phead, int val)
{
list* cur = phead;
while (cur->_next)
{
cur = cur->_next;
}
list* newnode = new list;
newnode->_next = nullptr;
newnode->_val = val;
cur->_next = newnode;
}
void print(list* phead)
{
assert(phead);
list* cur = phead->_next;
while (cur)
{
cout << cur->_val << " ";
cur = cur->_next;
}
cout << endl;
}
合并两个链表:
list* Merge(list*p1,list*p2)
{
if (p1 == nullptr)
{
return p2;
}
if (p2 == nullptr)
{
return p1;
}
list* ret = new list;
ret->_next = nullptr;
list* cur = ret;
list* cur1 = p1->_next;
list* cur2 = p2->_next;
while (cur1 && cur2)
{
if (cur1->_val > cur2->_val)
{
cur->_next = cur2;
cur2 = cur2->_next;
}
else
{
cur->_next = cur1;
cur1 = cur1->_next;
}
cur = cur->_next;
}
if (cur1 != nullptr)
{
cur->_next = cur1;
}
else
{
cur->_next = cur2;
}
return ret;
}
测试用代码:
void test()
{
list* l1 = new list;
list* l2 = new list;
l1->_next = nullptr;
l2->_next = nullptr;
push_back(l1,1);
push_back(l1,3);
push_back(l1,5);
push_back(l1,7);
push_back(l1,9);
push_back(l1,11);
push_back(l1,13);
push_back(l2, 2);
push_back(l2, 4);
push_back(l2, 6);
push_back(l2, 8);
push_back(l2, 10);
list* l3 = Merge(l1, l2);
print(l3);
}
int main()
{
test();
return 0;
}
输出结果: