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

来源:互联网 发布:it狂人女主角 编辑:程序博客网 时间:2024/06/10 02:53


/**

 *面试题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) {//把它插入到precur之间

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交流

0 0
原创粉丝点击