您的位置:首页 > 编程语言 > C语言/C++

面试题五 C/C++面试秘笈 之链表的正向排序--程序员面试题

2016-02-25 15:48 465 查看
/**
*面试题9
*单链表的正向排序
*/

typedef struct linkListSort{
int data;
linkListSort * next;
}linkListSort;

linkListSort * insert_sort(void)
{
structlinkListSort * head =
NULL,*New,*cur,*pre;
int data =0;
while (1) {
printf("please input the data:\n");
cin>>data;
if (data ==0) {//如果是0,结束
break;
}

New = (structlinkListSort*)malloc(sizeof(structlinkListSort));
New->data = data;
New->next =NULL;
if (head ==NULL) {
head = New;//在第一次循环时对head赋值
continue;
}
if (New->data <= head->data) {
//在head之前插入节点
New->next = head;
head = New;
continue;
}
cur = head;

if (New->data > cur->data && cur->next
!= NULL) { //找到需要插入的位置
pre = cur;
cur = cur->next;
}
if (cur->data >= New->data) {//把它插入到pre和cur之间
pre->next = New;
New->next = cur;

}else{
cur->next = New;
}
}

return head;
}

/**
*编程实现一个单链表的打印
*/
void linkListPrint(linkListSort *head)
{
int index =0;//总得个数
linkListSort *p;
if (head->next ==NULL) {//链表为空
cout<<"Link is empty!"<<endl;
return;
}
p = head->next;
while (p !=NULL) {//遍历链表
printf("the %dth is node:%d\n",++index,p->data);//打印链表元素
p = p->next;
}
}

如果有任何问题,欢迎下方留言谈论,或者加入QQ群83459374交流
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: