LeetCode 算法习题 第四周

来源:互联网 发布:火山软件开发平台 编辑:程序博客网 时间:2024/06/01 10:21

21. Merge Two Sorted Lists

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.

题目大意:

将两个有序的list 进行归并排序,默认从小到大的顺序。

我的解答:

/** * 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* result = new ListNode(0);        ListNode* back = result;        if((l1 == NULL) && (l2 == NULL)) return NULL;//两序列皆为空,则直接返回空 因为之前声明用于保存结果序列的result 时调用构造函数,第一项为0,所以要加此判断        if(l1 == NULL) return l2;        if(l2 == NULL) return l1;//如果某一序列为空,则直接返回另一非空序列。若不加此判断,则访问空序列节点的next项时会出现报错        while((l1 != NULL) && (l2 != NULL)){            if(l1 -> val < l2 -> val){                result -> val = l1 -> val;                result -> next = new ListNode(0);                result = result -> next;                if(l1 -> next != NULL) l1 = l1 -> next;                else l1 = NULL;            }            else {                 result -> val = l2 ->val;                result -> next = new ListNode(0);                result = result -> next;                if(l2 -> next != NULL) l2 = l2 -> next;                else l2 = NULL;            }        }//将较小项赋值给result,注意要给result的next节点声明空间,否则直接访问next会出现报错(为NULL),将较小项序列指针指向next项,同样需要判断next是否为空,若为空,则赋值为NULL        if(l1 != NULL){            while(l1 != NULL){                result -> val = l1 ->val;                if(l1->next != NULL){                result -> next = new ListNode(0);                result = result ->next;                }                if(l1 -> next != NULL)                l1 = l1 -> next;                else l1 = NULL;            }        }        if(l2 != NULL){            while(l2 != NULL){                result -> val = l2 ->val;                if(l2->next != NULL){                result -> next = new ListNode(0);                result = result ->next;                }                if(l2 -> next != NULL)                l2 = l2 -> next;                else l2 = NULL;            }        }//若一只序列为空,另一只还有项,则将剩余项全部放入result中,注意对next项先判断是否为空,再使用        return back;//返回result链的头结点    }};