Given an increasing ordered list L (leading node, element is integer), a program is written to insert a new integer into L, and keep the order of L The type definition of single chain table is as follows:
typedef int elementType;
typedef struct lnode
{ elementType data;
struct lnode *next;
}Lnode,* LinkList;
Input format:
Input in three lines
Number of elements in the first row
The value of the element in the second line, separated by spaces.
Element value to be inserted in the third line
Output format:
Output ordered list element values in a row, with a space before each element to separate it from the adjacent elements.
Input example:
5 1 3 5 7 9 4Output example:
1 3 4 5 7 9#include<stdio.h> #include<malloc.h> typedef int elementType; typedef struct lnode { elementType data; struct lnode *next; }Lnode; //Tail insertion method Lnode* CreateList(int a[],int n) { Lnode *p,*head,*node; int i; head = (Lnode*)malloc(sizeof(Lnode)); p = head; for(i = 0;i<n;i++) { node = (Lnode*)malloc(sizeof(Lnode)); node->data = a[i]; p->next = node; p = node; } p->next = NULL; return head; } void Insert(Lnode* head,int temp,int n) { Lnode *insert,*p; p = head->next; insert = (Lnode*)malloc(sizeof(Lnode)); int i; insert->data = temp; if(temp<p->data) { insert->next = p; head->next = insert; } for(i = 0;i<n-1;i++) { if((temp>p->data) && (temp<=p->next->data)) { insert->next = p->next; p->next = insert; } p = p->next; } if(temp>p->data) { p->next = insert; insert->next = NULL; } } void output(Lnode *head) { Lnode *p; p = head->next; while(1) { printf(" %d",p->data); if(p->next == NULL) { break; } p = p->next; } } int main() { Lnode *Linklist,*p; int n,i; int temp; scanf("%d",&n); if(n==0) { Linklist = (Lnode*)malloc(sizeof(Lnode)); scanf("%d",&temp); p = (Lnode*)malloc(sizeof(Lnode)); p->data = temp; Linklist->next = p; p->next= NULL; output(Linklist); return 0; } int a[n]; for(i = 0;i<n;i++) { scanf("%d",&a[i]); } scanf("%d",&temp); /*for(i = 0;i<n;i++) printf("%d",a[i]);*/ Linklist = CreateList(a,n); Insert(Linklist,temp,n); output(Linklist); return 0; }