面試題五 C/C++面試祕笈 之鏈表的正向排序--程序員面試題


/**

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

發佈了88 篇原創文章 · 獲贊 32 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章