您的位置:首页 > 其它

单向链表:在插入值的同时要进行排序

2010-04-07 11:06 239 查看
//作用:完成由Node类型结点构成的一个单向链表的由小到大

程序思路:

1、在新建结点时要注意给next指针随时赋上Null值;

2、在整个程序中一定要把头结点保存起来;

3、第一次插入结点时只需给头结点赋值即可;

4、在之后插入值时需要注意插入的位置,分三种情况:头结点、中间结点、尾结点

 

struct Node
{
struct Node *next;
int value;
};

struct Node* InsertSort(void)
{
Node *nNew = NULL;
Node *nHeard = NULL;

for (int n = 0; n < 5; ++n)
{
nNew = new Node;
if (NULL == nNew)
{
return NULL;
}
else
{
printf("请输入值:");
scanf("%d", &(nNew->value));

nNew->next = NULL;//注意此处随使用给赋值为NULL
}

if (nHeard == NULL)//第一次插入值只需给头结点赋值勤
{
nHeard = nNew;
continue;
}

if (nNew->value < nHeard ->value)//判断插入的值是不是头结点
{
nNew->next = nHeard;
nHeard = nNew;

continue;
}

//根据头结点依次向后进行比较值
Node *nCur = nHeard;
while (nNew->value > nCur->value)
{
if (nCur->next == NULL)
{
break;
}

nCur = nCur->next;
}

//判断插入的值是否是尾结点
if (nCur->next == NULL)
{
nCur->next = nNew;
}
else
{
nNew->next = nCur->next;
nCur->next = nNew;
}
}

return nHeard;
}

void print(struct Node* Head)
{
struct Node* nCur;
nCur = Head;

while(nCur!=NULL)
{
printf("当前值=%d/n",nCur->value);
nCur = nCur->next;
}
}

int main(int argc, char * argv[])
{

struct Node* head;
head=InsertSort();
print(head);

system("pause");
return 0;
}
  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struct null system