LeetCode#21 Merge Two Sorted Lists

来源:互联网 发布:数据新闻啥意思 编辑:程序博客网 时间:2024/06/07 10:34

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.

题意:就是给你两个已经排好序的链表,然后叫你合并成一个链表。
思路:就是考链表的操作。代码:

/** * 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 *t1=l1;        ListNode *t2=l2;        ListNode *head=new ListNode(0);      //new的应用很巧妙  不用再malloc了        ListNode *temp=head;        while(t1!=NULL||t2!=NULL)        {            while((t2==NULL&&t1!=NULL)||(t1!=NULL&&t1->val<=t2->val))            {                temp->next=t1;                temp=temp->next;                t1=t1->next;            }            while((t1==NULL&&t2!=NULL)||(t2!=NULL&&t1->val>t2->val))            {                temp->next=t2;                temp=temp->next;                t2=t2->next;            }        }        temp->next=NULL;        return head->next;    }};