Require:
This problem requires the implementation of a function that inserts a new integer into an increasing linked list of integer sequences (the leading node) and keeps the sequence in order.
Function interface definition:
List Insert( List L, ElementType X );
where the List
structure is defined as follows:
typedef struct Node *PtrToNode;
struct Node {
ElementType Data; /* 存储结点数据 */
PtrToNode Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */
L
It is a given singly linked list with a head node, and the data stored in the node is in increasing order; the function Insert
needs to X
insert L
and keep the order of the sequence, and return the pointer of the inserted linked list head.
Example of the referee test procedure:
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表 */
List Insert( List L, ElementType X );
int main()
{
List L;
ElementType X;
L = Read();
scanf("%d", &X);
L = Insert(L, X);
Print(L);
return 0;
}
/* 你的代码将被嵌在这里 */
Input sample:
5
1 2 4 5 6
3
Sample output:
1 2 3 4 5 6
Code:
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表 */
List Insert( List L, ElementType X );
int main()
{
List L;
ElementType X;
L = Read();
scanf("%d", &X);
L = Insert(L, X);
Print(L);
return 0;
}
/* 你的代码将被嵌在这里 */
/*
* @Description : 创建一个用户定义的链表
* @param : 无
* @return : 新的的链表
*/
List Read()
{
int n;
scanf("%d", &n);
//为头节点申请空间
List Head = (List)malloc(sizeof(PtrToNode));
//防止野指针的出现
Head->Next = NULL;
//当n不是0的时候
if (n != 0){
//创建一个指针
List p = Head;
for (int i = 0; i < n; i++){
//创建一个中间节点
List Var = (List)malloc(sizeof(PtrToNode));
//尾插法
scanf("%d", &(Var->Data));
//p的指针指向新的元素
p->Next = Var;
//p后移动
p = Var;
}
//安全起见,尾指针为空
p->Next = NULL;
}
return Head;
}
/*
* @Description : 打印链表
* @param -L : 需要打印的链表
* @return : 无
*/
void Print( List L )
{
//先找到第一个结点,判断是不是空
L = L->Next;
if (L == NULL){
printf("NULL");
}
else{
while (L){
printf("%d ",L->Data);
L = L->Next;
}
}
printf("\n");
}
/*
* @Description : 插入新整数
* @param -L : 插入的序列链表
* @param -X : 要插入的数据
* @return : 更改后的链表
*/
List Insert( List L, ElementType X )
{
List Ver = (List)malloc(sizeof(PtrToNode));
List p = L;
//找到第一个结点
List l = L->Next;
while (l != NULL){
if (l->Data > X) {
break;
}
p = l;
l = l->Next;
}
Ver->Data = X;
Ver->Next = l;
p->Next = Ver;
return L;
}