您的位置:首页 > 其它

lintcode:Merge Two Sorted Lists

2016-03-07 15:18 417 查看
Merge two sorted (ascending) linked lists and return it as a new

sorted list. The new sorted list should be made by splicing together

the nodes of the two lists and sorted in ascending order.

Given 1->3->8->11->15->null, 2->null ,

return 1->2->3->8->11->15->null.

题目很简单。

注意一点,最后如果p1或者p2非空时,只需要把p1或p2链接到newp->next即可,而不需要逐个的元素添加。

/**
* Definition of ListNode
* class ListNode {
* public:
*     int val;
*     ListNode *next;
*     ListNode(int val) {
*         this->val = val;
*         this->next = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode *newl=new ListNode(0);
ListNode *newp=newl;

ListNode *p1=l1,*p2=l2;
while(p1 && p2){

if(p1->val<p2->val){
newp->next=p1;
newp=newp->next;
p1=p1->next;
}else{
newp->next=p2;
newp=newp->next;
p2=p2->next;
}

}

if(p1){
newp->next=p1;
}else{
newp->next=p2;
}

return newl->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: