您的位置:首页 > 其它

Merge Two Sorted Lists

2015-03-13 20:40 183 查看
两个指针的做法,但比起2个数组有序的数组的话,链表做更容易,因为当一个链表遍历结束后,tail指针并不需要遍历另一个链表,只要直接指向它就行

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) {
struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *tail = head;
while(l1&&l2){
if(l1->val<l2->val){
tail->next = l1;
l1 = l1->next;
}else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
//很傻比的后面全部遍历一遍
while(l1){
tail->next = l1;
l1 = l1->next;
tail = tail->next;
}
while(l2){
tail->next = l2;
l2 = l2->next;
tail = tail->next;
}
return head->next;
}


/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) {
struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *tail = head;
while(l1&&l2){
if(l1->val<l2->val){
tail->next = l1;
l1 = l1->next;
}else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
if(!l1)tail->next = l2;
else if(!l2) tail->next = l1;
return head->next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: