题目:Merge Two Sorted Lists
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.
简单题,只要对两个链表中的元素进行比较,然后移动即可,只要对链表的增删操作熟悉,几分钟就可以写出来,代码如下:
struct ListNode {
int val;
ListNode *next;
ListNode(int x):val(x), next(NULL) {}
}; ListNode *GetLists(int n) //得到一个列表
{
ListNode *l = new ListNode();
ListNode *pre = l;
int val;
for (int i = ; i < n; i ++) {
cin >> val;
ListNode *newNode = new ListNode(val);
pre->next = newNode;
pre = pre->next;
}
return l->next;
} ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
assert (NULL != l1 && NULL != l2);
if (NULL == l1 && NULL == l2)
return NULL;
if (NULL == l1 && NULL != l2) // !!要记得处理一个为空,另一个不为空的情况
return l2;
if (NULL != l1 && NULL == l2)
return l1; ListNode *temp = new ListNode();
temp->next = l1;
ListNode *pre = temp; while(NULL != l1 && NULL != l2) {
if (l1->val > l2->val) { //从小到大排列
ListNode *next = l2->next;
l2->next = pre->next;
pre->next = l2;
l2 = next;
}
else {
l1 = l1->next;
}
pre = pre->next;
}
if (NULL != l2) {
pre->next = l2;
}
return temp->next;
}
这其中要注意一点,即要记得处理一个链表为空,另一个不为空的情况,如{}, {0} -- > {0},当然上面的写法多少啰嗦了一些,可以简写。