Merge Two Sorted Lists(LeetCode)

来源:互联网 发布:ubuntu华屏 编辑:程序博客网 时间:2024/06/07 15:00

题目: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) {         if(l1==NULL && l2==NULL)return NULL;if(l1==NULL && l2!=NULL)return l2;if(l1!=NULL && l2==NULL)return l1;ListNode *head=NULL,*p=l1,*q=l2;if(p->val<=q->val){    head=l1;    p=p->next;}else{    head=l2;    q=q->next;}ListNode* tail=head;//tail指向新链表的尾部,尾插法while(p!=NULL && q!=NULL){    if(p->val<=q->val){        tail->next=p;        p=p->next;    }else{        tail->next=q;        q=q->next;    }    tail=tail->next;//尾插法,tail始终指向新链表的尾部,插入一个值,tail后移一次}if(p!=NULL)    tail->next=p;if(q!=NULL)    tail->next=q;return head;        }};

0 0