/**
*面試題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交流