单链表排序
View Code
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node* next; }Link; int a[10]={12,34,503,2,12,5,74,7,112,6}; Link* CreateLink() { int i; Link *head,*tail; head=(Link* )malloc(sizeof(Link)); head->data=0; tail=head; Link* p; for (i=0; i<10; ++i) { p=(Link* )malloc(sizeof(Link)); p->data=a[i]; p->next=NULL; if (head==NULL) { head->next=p; tail=p; } else { tail->next=p; tail=p; } } return head; } /******选择排序*******/ void SelectSort(Link* head) { if (head==NULL) { return; } Link *p=head->next; Link *q, *min; int temp; for (;p;p=p->next) { min=q=p; for (;q;q=q->next) { if (min->data > q->data) { min=q; } } temp=min->data; min->data=p->data; p->data=temp; } } /*******冒泡排序********/ void BubbleSort(Link* head) { if (head==NULL) { return; } int k=0; int i=0; Link *p=head->next; Link *q; while(p) { k++; p=p->next; } p=head->next; for (;p;p=p->next) { for(q=head->next;q->next && k-i>0; q=q->next) { if (q->data > q->next->data) { int temp=q->next->data; q->next->data=q->data; q->data=temp; } } i++; } } /*******插入排序******/ void InsertSort(Link* head) { if (head==NULL) { return; } Link *p=head; Link *q=p->next; Link *m=q; Link *n=m->next; while(n) { while(q!=n && q->data < n->data) { p=p->next; q=q->next; } if (q==n) { p=head; q=p->next; m=m->next; n=n->next; } else { m->next=n->next; n->next=q; p->next=n; n=m->next; p=head; q=p->next; } } } void PrintLink(Link* head) { if (head==NULL) { return; } Link* p=head->next; while(p) { printf("%d ",p->data); p=p->next; } } int main() { Link* head; head=CreateLink(); BubbleSort(head); //SelectSort(head); //InsertSort(head); PrintLink(head); return 0; }
#include <iostream> #include <vector> using namespace std; /* void Permutation_Solution1(char *p, int begin, int end) { if(end-1==begin) { for(int i=0; i<end; ++i) { cout<<p[i]; } cout<<endl; } else { for(int k=begin; k<end; ++k) { swap(p[k],p[begin]); Permutation_Solution1(p,begin+1,end); swap(p[k],p[begin]); } } } */ /* void Permutation_Solution2(char *pbegin, char *pend) { if(*pend=='\0') { cout<<pbegin<<endl; } else { char *p=pend; while(*p!='\0') { swap(*pend,*p); Permutation_Solution2(pbegin,pend+1); swap(*pend,*p); p++; } } } */ void Permutation_Solution1(int num , int sum, vector<int> &result, int *total) { if(sum<0 || num*10<sum) { return; } if(num==1) { if(sum<=10) { for(vector<int>::iterator iter=result.begin(); iter!=result.end(); ++iter) { cout<<*iter<<" "; } cout<<endl; (*total)++; return; } else { return; } } else { for(int i=1; i<=10; ++i) { result.push_back(i); Permutation_Solution1(num-1,sum-i,result,total); result.pop_back(); } } } void Permutation_Solution(int num, int sum) { vector<int> result; int total=0; Permutation_Solution1(num,sum,result, &total); cout<<total<<endl; } int main() { Permutation_Solution(10,96); return 0; }