问题描述:
将两个排序链表合并为一个新的排序链表。
实现思路:
先考虑链表为空的情况,当两个链表不同时为空时。初始时,先比较两个链表第一个节点的值的大小。把节点小的插入新链表中,在节点值小的链表中向后移动一个节点。当其中有一个链表为空时,直接把另一个链表接在新链表中。
代码:
/**
* 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 *p , *q , *r , *s;
r= new ListNode(0);
s= r;
while (l1!= NULL && l2!= NULL) {
if (l1->val> l2->val) {
ListNode *temp= l2->next;
s->next= l2;
s= s->next;
l2= temp;
} else {
ListNode *temp= l1->next;
s->next= l1;
s= s->next;
l1= temp;
}
}
if (l1!= NULL) {
s->next= l1;
}
if (l2!= NULL) {
s->next= l2;
}
return r->next;
}
};
感想:
考虑链表其中有一个先为空的情况。比较时,只需将值小的节点放入新链表中,节点后移。