您的位置:首页 > 其它

[LeetCode OJ]Merge Two Sorted Lists

2014-10-21 21:20 399 查看
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.

感觉这道题对自己的帮助还是挺大的,对于链表和指针都有一个更好的理解。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *p;
ListNode *q;
ListNode *temp;
ListNode *head;

if(l1 == NULL && l2 == NULL)
return NULL;
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;

p = l1;
q = l2;
head = NULL;
if(p->val < q->val) {
head = p;
p = p->next;
}
else {
head = q;
q = q->next;
}
temp = head;
while(p && q) {
if(p->val < q->val) {
temp->next = p;
p = p->next;
}
else {
temp->next = q;
q = q->next;
}
temp = temp->next;
}
if(p != NULL) {
temp->next = p;
}
else {
temp->next = q;
}
return head;
}
};


头指针head赋给temp那一下反应了不短的时间,想明白以后觉得自己好蠢啊= =
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: