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; }
}