大致思想:
先申请一节点,head头指针总是指向最小,每插入一个点,就有第一个节点开始比较,直到新的节点小于当前节点时,便插入到当前节点之前,由此可见,要申请记忆节点rh和q,具体算法代码如下:
#include <stdio.h>
#include <malloc.h>
struct Node
{
int data;
Node *next;
};
Node *CreateNode(Node *head,int n)
{
Node *p,*q,*r;
head=(Node *)malloc(sizeof(Node));
head->next=NULL;
q=(Node *)malloc(sizeof(Node));
r=(Node *)malloc(sizeof(Node));
for(int i=n;i>0;i--)
{
p=(Node *)malloc(sizeof(Node));
scanf("%d",&p->data);
if(i==n)
{
p->next=head->next;
head->next=p;
}
else
{
q=head->next;r=head;
while(q && q->data <p->data)
{
r=q;
q=q->next;
}
r->next=p;
p->next=q;
}
}
return head;
}
void main()
{
Node *head;
int n;
printf("input the number of node : ");
scanf("%d",&n);
printf("input the node\n");
head=CreateNode(head,n);
while(head->next!=NULL)
{
head=head->next;
printf("%d, ",head->data);
}
}