leetcode_21 question--merge, Sorted Lists (linked list)

Source: Internet
Author: User

Merge Sorted ListsTotal accepted:61585 Total submissions:188253my submissions QuestionSolution

Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.

Hide TagsLinked ListHas you met this question in a real interview? Yes No

discuss

#include <iostream>using namespace std;struct listnode {int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}}; listnode* mergetwolists (listnode* L1, listnode* L2) {if (l1==null) return l2;if (l2==null) return L1; ListNode *ptr1=l1;//l1,l2 as the remaining list of the new linked lists OH current head node pointer listnode *ptr2=l2;//listnode *temp;//new linked list tail node pointer ListNode *root;// Final head node if (l1->val<l2->val) {temp=l1;root=l1;ptr1=l1->next;ptr2=l2;} Else{temp=l2;root=l2;ptr1=l1;ptr2=l2->next;} while (1) {if (ptr2==null&&ptr1==null) break;if (ptr1==null&&ptr2!=null) {temp->next=ptr2;break;} if (ptr1!=null&&ptr2==null) {temp->next=ptr1;break;} if (ptr1->val<ptr2->val) {temp->next=ptr1;ptr1=ptr1->next;temp=temp->next;} Else{temp->next=ptr2;ptr2=ptr2->next;temp=temp->next;}} return root;} int main () {ListNode *root1=new ListNode (2); ListNode *root2=new ListNode (1); ListNode *ptr=mergetwolists (root1,root2);cout<<ptr->val<< ' <<ptr->next->val<< Endl;}

  

leetcode_21 question--merge, Sorted Lists (linked list)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.