题目:https://oj.leetcode.com/problems/merge-two-sorted-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 *head,*p,*q,*r;
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
p = l1;
q = l2;
head = NULL;
r = NULL;
if(p -> val > q->val){
head = q;
q =q -> next;
}
else {
head = p;
p = p->next;
}
r = head;
r->next =NULL;
while(p!=NULL&&q!=NULL){
if(p->val > q->val){
r->next = q;
r = r->next;
q = q ->next;
}
else{
r->next = p;
r = r->next;
p = p ->next;
}
}
if (p)<span style="white-space:pre"> </span>//这里原先我还比较笨的写了一个循环,切记直接接入后面的内容就行了,链表还是用的不熟
r->next = p;
else if (q)
r->next = q;
return head;
}
};
再来一个高端算法,用的是递归,思路跟一般的俩数组排序一样,每次递归都将ret赋值好,用next去找下一次递归的结果,这样到下一次递归的时候,又重新赋值好下一个ret的本体,这个过程相当于r=p->next;r=r->next;
/**
* 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) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode *ret = NULL;
if (l1->val < l2->val)
{
ret = l1;
ret->next = mergeTwoLists(l1->next, l2);
}
else
{
ret = l2;
ret->next = mergeTwoLists(l1, l2->next);
}
return ret;
}
};