//随机生成100个数,做插入排序,链表的练习
随机生成100个数,做插入排序,链表的练习 #include <iostream> #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node* next; }; void insert(node * tnode,node* thead) { node *itr = thead; if(tnode->data <thead->data) { tnode->next = thead; thead = tnode; return ; } while(itr) { if(((tnode->data) > (itr->data))&&(itr->next != NULL)&&(tnode->data >itr->next->data)) itr = itr->next; else { tnode->next = itr->next; itr->next = tnode; return; } } } int main() { int temp = 100; node *head = (node*)malloc(sizeof(node)); head->data = 0; head->next = NULL; int _data; printf("插入排序前的数据为:\n"); //生成数据 while(temp--) { _data = rand()%1000; node *_node = (node*)malloc(sizeof(node)); _node->data = _data; _node->next = NULL; if(head==NULL) //判断是否为第一个结点 { head = _node; continue; } int m; insert(_node,head); } printf("排序后的数据为:\n"); node *itr = head; int ii = 0,jj = 0,flag2 = 0; for(int i = 0;i<100;i++) { if(itr!=NULL) { ii = itr->data; if(itr->next!=NULL) { jj = itr->next->data; if(ii>jj) flag2 = 1; } printf("%d\n",itr->data); itr = itr->next; } else break; } if(flag2==0) printf("结果正确"); else printf("结果错了"); return 0; } void insert(node *n,node* &head){ if(head == NULL){ head = n; return; } node *p = head; node *q = p->next; while(q != NULL && p->data < n->data){ p = p->next; q = q->next; } p->next = n; n->next = q; }
注意头指针的处理啊