Merge two sequential list __ Merge

Source: Internet
Author: User

Similarly, merging two ordered arrays or lists is also a classic question in the offer of a sword. The topic is described as follows: Enter two ascending sorted lists, merge the two linked lists, and keep the nodes in the new list sorted by increment. I do this by merging the linked lists.

Here, do not need to create a new linked list, as long as there are three node pointers on the line, the first node pointer Node1 to the first linked list, the second node pointer Node2 point to the second linked list, the third node pointer Node3 point to the new list. The simple schematic diagram is as follows:






When the next node is in the first linked list, Node3 points to the node, node1++, and so on. Until one of the linked lists is empty, the other list is received Node3. Note that the requirements of the topic is two lists are ordered. Complete code uploaded to Https://github.com/chenyufeng1991/MergeTwoSortList.

The core code is as follows:

void Mergelist (node *pfirstlist, node *psecondlist, node **pmergedlist) {*pmergedlist = new node;
    memset (*pmergedlist, 0, sizeof (Node));

    (*pmergedlist)->next = NULL;
    Node *pfirstmove = pfirstlist->next;
    Node *psecondmove = psecondlist->next;

    Node *pmergedmove = *pmergedlist; while (pfirstmove!= null && psecondmove!= null) {if (pfirstmove->element <= psecondmove->e
            lement) {pmergedmove->next = Pfirstmove;
        Pfirstmove = pfirstmove->next;
            else {pmergedmove->next = Psecondmove;
        Psecondmove = psecondmove->next;
    } Pmergedmove = pmergedmove->next;
        while (Pfirstmove!= NULL) {pmergedmove->next = Pfirstmove;
        Pfirstmove = pfirstmove->next;
    Pmergedmove = pmergedmove->next;
      while (Psecondmove!= NULL) {pmergedmove->next = Psecondmove;  Psecondmove = psecondmove->next;
    Pmergedmove = pmergedmove->next; }
}

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.