源代码:
#include <stdio.h>
#include <malloc.h>
//定义结构体//
typedef struct node{
int data;
struct node *next;
}node,*linklist;
void nodeTest(){
struct node *head,*p,*q,*t;
int i,n,a;
head=p=NULL;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&a);
p = (struct node *)malloc(sizeof(struct node));
p->data = a;
p->next = NULL;
if(head == NULL){
head = p;
}
else
q->next = p;
q = p;
}
//输出链表//
t = head;
while(t != NULL){
printf("%d",t->data);
t = t->next;
}
//输入要插入的节点的值//
scanf("%d",&a);
t = head;
//进行判断和插入//
while( t != NULL){
if(t->next == NULL || t->next->data > a){
struct node *d = (struct node *)malloc(sizeof(struct node));
d->data = a;
d->next = t->next;
t->next = d;
break;
}
t = t->next;
}
//将插入后的链表输出
t = head;
while(t != NULL){
printf("%d",t->data);
t = t->next;
}
return;
}
int main(){
nodeTest();
return 0;
}
测试结果: