Title Link: https://pintia.cn/problem-sets/434/problems/5726
1. If the topic does not give us a list of the original increment sequence, then we can consider inserting the node when creating the original linked list, that is, when creating the original linked list, each read into a data, compare the data with the data to be inserted, if it is found that the data to be inserted is less than equal to the data just read in, Then we first link the nodes that need to be inserted to the footer, link the data nodes just read into the footer, and then continue to create the linked list, but in order to prevent repeated insertions that need to insert the data, we need to set a flag = 0; When the insert is complete, the flag is set to 1 so that it is not repeatedly inserted.
Here is the implementation code for this idea:
1#include <stdio.h>2#include <stdlib.h>3 4typedefintElementType;5typedefstructnode*List;6 structnode{7 ElementType Data;8 List Next;9 };Ten One intMain () A { - intN, M, DT, flag; -Flag =0; the List Front, rear, tmp; -Front = Rear = (List)malloc(sizeof(structNode)); - -scanf_s ("%d%d", &n, &M); + GetChar (); - + if(N = =0)//if the original linked list is empty, insert directly A { atTMP = (List)malloc(sizeof(structNode)); -Tmp->data =M; -Tmp->next =NULL; -Rear->next =tmp; -Rear =tmp; - } in - while(n--)//if the original list is not empty, insert to { +scanf_s ("%d", &DT); - GetChar (); the if(M <= dt && flag = =0) * { $Flag =1;Panax NotoginsengTMP = (List)malloc(sizeof(structNode)); -Tmp->data =M; theTmp->next =NULL; +Rear->next =tmp; ARear =tmp; the } +TMP = (List)malloc(sizeof(structNode)); -TMP->data =DT; $TMP--Next =NULL; $Rear-Next =tmp; -Rear =tmp; - } theTMP = FrontNext; - for(;tmp->next; tmp = tmp->Next)Wuyiprintf"%d", tmp->Data); theprintf"%d\n", tmp->Data); - Wu - return 0; About}
2. The following is a general solution to this problem:
1 list Insert (list L, ElementType X)2 {3 List Prenode, Insnode;4Prenode =L;5 for(; Prenode->next && Prenode->next->data < X; Prenode = prenode->Next);6Insnode = (List)malloc(sizeof(structNode));7Insnode->data =X;8Insnode->next = prenode->Next;9Prenode->next =Insnode;Ten returnL; One}
2-4 incrementing a list insert