快考二级了吧,送你段排序算法要不要啊?
剑栈风樯各苦辛,别时冰雪到时春
#include<stdio.h> #include<stdlib.h> typedef struct Node{ int data; Node *next; }Node; void sortBubble(Node *head) { Node *h=head->next,*last=head; while(last->next!=NULL) { last=last->next; } for(Node *r=h;r->next!=NULL;r=r->next) { Node *loc=head; while(loc!=last) { loc=loc->next; } last=loc; for(Node *c=h;c->next!=NULL&&c!=loc;c=c->next) { if(c->data>c->next->data) { c->data=c->data+c->next->data; c->next->data=c->data-c->next->data; c->data=c->data-c->next->data; // display(head); } } } } void display(Node *head) { Node *h=head->next; while(h!=NULL) { printf("%3d",h->data); h=h->next; } printf("\n"); } main() { Node *head=(Node *)malloc(sizeof(Node)); Node *h=head; int a[]={7,2,1,6,5,3,4}; for(int i=0;i<7;i++) { Node *newNode=new Node(); newNode->data=a[i]; newNode->next=NULL; h->next=newNode; h=h->next; } h=NULL; sortBubble(head); display(head); }
#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; Node *next; }Node; Node *head; void LinkList(int a[],int len) { head=(Node*)malloc(sizeof(Node)); Node *h=head; for(int i=0;i<len;i++) { Node *newNode=(Node*)malloc(sizeof(Node)); newNode->data=a[i]; newNode->next=NULL; h->next=newNode; h=h->next; } h=NULL; } void sort(Node *head) { Node *h=head; for(Node *rd=h->next;rd->next!=NULL;rd=rd->next) { Node *cd=rd->next; if(cd->data<rd->data) { int temp=cd->data; Node *ha=h,*hb=h; while(temp>ha->next->data) { ha=ha->next; } while(hb->next!=rd)hb=hb->next; rd->next=cd->next; cd->next=ha->next; ha->next=cd; rd=hb; } } } void display(Node *head){ Node *h=head->next; while(h!=NULL) { printf("%d\t",h->data); h=h->next; } } main() { int a[]={4,2,1,3,6,5,7}; LinkList(a,7); sort(head); display(head); }