LeetCode-021 Merge Two Sorted Lists

来源:互联网 发布:java中的final关键字 编辑:程序博客网 时间:2024/06/07 13:52

Description

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.

Example

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Analyse

合并两个有序链表为一个新的有序链表,操作上没有什么好讲的,需要注意的就是当一个链表跑到头的时候,需要把另外一个链表剩下的成员接上去。

Code

/** * 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* ans=NULL;        ListNode* head;        while (l1!=NULL || l2!=NULL) {            int num;            if (l1==NULL) {                num=l2->val;                l2=l2->next;            } else             if (l2==NULL) {                num=l1->val;                l1=l1->next;            } else             if (l1->val<l2->val) {                num=l1->val;                l1=l1->next;            } else {                num=l2->val;                l2=l2->next;            }            if (ans==NULL) {                ans=new ListNode(num);                head=ans;            } else {                ListNode *temp=new ListNode(num);                ans->next=temp;                ans=ans->next;            }        }        if (ans==NULL) return NULL;        return head;    }};
原创粉丝点击