链表插入排序,有错!
#include<stdio.h>#include<stdlib.h>typedef struct node *link;struct node { int item; link next;};link InsertSort(link head);int main(){ int i; int N; link heada,x,y; while (scanf("%d", &N) == 1) { heada = (struct node *)malloc (sizeof(struct node)); x = heada; heada->next = NULL; //构造链表 for (i = 1; i <= N; i++) { x = (x->next = (struct node *)malloc(sizeof(struct node))); x->item = rand()%1000; x->next = NULL; } //插入排序 y = InsertSort(heada); while (y) { printf("%-4d", y->item); y = y->next; } } return 0;}//插入排序函数link InsertSort(link heada){ link headb,a,b,t,u,x; headb = (struct node *)malloc (sizeof(struct node)); a = heada; b = headb; b->next = NULL; for (t = a->next; t != NULL; t = u) { u = t->next; for (x = b; x != NULL; x = x->next) { if (x->next->item > t->item)//断点后这里有错 break; } t->next = x->next; x->next = t; } return headb;}
#include<stdio.h>#include<stdlib.h>typedef struct node *link;struct node { int item; link next;};link InsertSort(link head);int main(){ int i; int N; link heada,x,y; while (scanf("%d", &N) == 1) { heada = (struct node *)malloc (sizeof(struct node)); x = heada; heada->next = NULL; //构造链表 for (i = 1; i <= N; i++) { x = (x->next = (struct node *)malloc(sizeof(struct node))); x->item = rand()%1000; x->next = NULL; } //插入排序 y = InsertSort(heada); while (y) { printf("%-4d", y->item); y = y->next; } } return 0;}//插入排序函数link InsertSort(link heada){ link headb,a,b,t,u,x; headb = (struct node *)malloc (sizeof(struct node)); a = heada; b = headb; b->next = NULL;//b的next为NULL for (t = a->next; t != NULL; t = u) { u = t->next; for (x = b; x != NULL; x = x->next) { if (x->next->item > t->item)//断点后这里有错---->b的next为NULL x初值为b b->next为 NULL,对NULL取->item自然要出错 break; } t->next = x->next; x->next = t; } return headb;}
[解决办法]
#include<stdio.h>#include<stdlib.h>typedef struct node { int item; struct node* next;}*link;link InsertSort(link head);int main(){ int i; int N; link heada,x,y;// srand(time(0)); while (scanf("%d", &N) == 1) { heada = (struct node *)malloc (sizeof(struct node)); x = heada; heada->next = NULL; //构造链表 for (i = 1; i <= N; i++) { x = (x->next = (struct node *)malloc(sizeof(struct node))); x->item = rand()%1000; x->next = NULL; } //插入排序 y = InsertSort(heada); y = y->next; while (y) { printf("%-4d", y->item); y = y->next; } } return 0;}//插入排序函数link InsertSort(link heada){ link headb,a,b,t,u,x; headb = (struct node *)malloc (sizeof(struct node)); a = heada; b = headb; b->next = NULL; for (t = a->next; t != NULL; t = u) { u = t->next; for (x = b; x != NULL; x = x->next) { if (x->next==NULL || x->next->item > t->item)//断点后这里有错 break; } t->next = x->next; x->next = t; } return headb;}