struct link { int data; link* next;};bool IsLoop(link* head){ link* p1=head, *p2 = head; if (head ==NULL || head->next ==NULL) { return false; } do{ p1= p1->next; p2 = p2->next->next; } while(p2 && p2->next && p1!=p2); if(p1 == p2) return true; else return false;}2,链表反转 struct linka { int data; linka* next;};void reverse(linka*& head){ if(head ==NULL) return; linka*pre, *cur, *ne; pre=head; cur=head->next; while(cur) { ne = cur->next; cur->next = pre; pre = cur; cur = ne; } head->next = NULL; head = pre;}linka* reverse(linka* p,linka*& head){ if(p == NULL || p->next == NULL) { head=p; return p; } else { linka* tmp = reverse(p->next,head); tmp->next = p; return p; }}3,判断两个数组中是否存在相同的数字 bool findcommon(int a[],int size1,int b[],int size2){ int i; for(i=0;i { int start=0,end=size2-1,mid; while(start<=end) { mid=(start+end)/2; if(a[i]==b[mid]) return true; else if (a[i] end=mid-1; else start=mid+1; } } return false;}bool findcommon2(int a[], int size1, int b[], int size2){ int i=0,j=0; while(i { if(a[i]==b[j]) return true; if(a[i]>b[j]) j++; if(a[i] i++; } return false;}4,最大子序列 int max_sub(int a[],int size){ int i,j,v,max=a[0]; for(i=0;i { v=0; for(j=i;j { v=v+a[j];//Sum(i, j+1) = Sum(i, j) + A[j+1] if(v>max) max=v; } } return max;}int max_sub2(int a[], int size){ int i,max=0,temp_sum=0; for(i=0;i { temp_sum+=a[i]; if(temp_sum>max) max=temp_sum; else if(temp_sum<0) temp_sum=0; } return max;}link* mid(link* head){ link* p1,*p2; p1=p2=head; if(head==NULL || head->next==NULL) return head; do { p1=p1->next; p2=p2->next->next; } while(p2 && p2->next); return p1;}6,按单词反转字符串 char* reverse_word(const char* str){ int len = strlen(str); char* restr = new char[len+1]; strcpy(restr,str); int i,j; for(i=0,j=len-1;i { char temp=restr[i]; restr[i]=restr[j]; restr[j]=temp; } int k=0; while(k { i=j=k; while(restr[j]!=' ' && restr[j]!='' ) j++; k=j+1; j--; for(;i { char temp=restr[i]; restr[i]=restr[j]; restr[j]=temp; } } return restr;} char temp=restr[i]; restr[i]=restr[j]; restr[j]=temp; restr[i]^=restr[j]; restr[j]^=restr[i]; restr[i]^=restr[j];7,字符串反转
#include #include #include using namespace std;//reverse the string 's1' except the substring 'token'.const char* reverse(const char* s1, const char* token){ assert(s1 && token); stack stack1; const char* ptoken = token, *head = s1, *rear = s1; while (*head != '') { while(*head!= '' && *ptoken == *head) { ptoken++; head++; } if(*ptoken == '')//contain the token { const char* p; for(p=head-1;p>=rear;p--) stack1.push(*p); ptoken = token; rear = head; } else
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7196059/viewspace-1000617/
,如需转载,请注明出处,否则将追究法律责任。