拓扑排序
连续最大子序列
KMP字符串匹配算法 国外论文-
http://www.ics.uci.edu/~eppstein/161/960227.html
字符串反转
原地逆序
char* Reverse(char* s)
{
// p指向字符串头部
char* p = s ;
// q指向字符串尾部
char* q = s ;
while( *q )
++q ;
q -- ;
// 交换并移动指针,直到p和q交叉
while(q > p)
{
char t = *p ;
*p++ = *q ;
*q-- = t ;
}
return s ;
}
不允许临时变量的逆序
// 使用异或操作对字符串s进行逆序
char* Reverse(char* s)
{
char* r = s ;
//令p指向字符串最后一个字符
char* p = s;
while (*(p + 1) != '\0')
++p ;
// 使用异或操作进行交换
while (p > s)
{
*p = *p ^ *s ;
*s = *p ^ *s ;
*p = *p-- ^ *s++ ;
}
return r ;
}
按单词逆序
给定一个字符串,按单词将该字符串逆序,比如给定"This is a sentence",则输出是"sentence a is This",为了简化问题,字符串中不包含标点符号。
void ReverseWord(char* p, char* q)
{
while(p < q)
{
char t = *p ;
*p++ = *q ;
*q-- = t ;
}
}
char* ReverseSentence(char *s)
{
char *p = s ; // point to the first char of a word
char *q = s ; // point to a white space or '\0'
while(*q != '\0')
{
if (*q == ' ')
{
ReverseWord(p, q - 1) ;
q++ ; // move to next word
p = q ;
}
else
q++ ;
}
ReverseWord(p, q - 1) ; // Reverse the last word
ReverseWord(s, q - 1) ; // Reverse the whole sentence
return s ;
}
以下是自己写的时候犯错误的方法,注意if 判断的条件不能随便调换,否则后果很严重
//错误的方法:先判断不是空格,因为'\0'也不是空格
void ReserveSentence1(char* s)
{
char* p=s;
char* q=s;
while(*q!='\0')
{
if(*q!=' ')
{
q++;
}
else
{
ReserveWord(p,q-1);
q++;
p=q;
}
}
}
对于我这个菜鸟而言,在测试这些代码的时候,传参发生了错误,在此提醒一下自己
注意字符串的定义
void main()
{
char *str="I am a boy, I like YY"; //常量区域
char s[] = "I am a boy, I like YY"; //变量区域
char t[] = "I am a boy I like YY very much"; //变量区域
Reverse(s);
//函数体不能改变常量区域的指针,我这个菜鸟一只犯错
//Reverse(str); 错误的传参
cout<<s<<endl;
ReserveSentence(t);
cout<<t<<endl;
system("pause");
}
字符串相似度
随机数生成
链表
struct LinkNode
{
int data;
LinkNode* next;
};
链表的反转
LinkNode* ReverseList(LinkNode* head)
{
LinkNode* pReverseHead=NULL;
LinkNode* pNode=head;
LinkNode* pPrev=NULL;
LinkNode* next=NULL;
while(pNode!=NULL)
{
next=pNode->next;
if(next==NULL)
pReverseHead=pNode;
pNode->next=pPrev;
pPrev=pNode;
pNode=next;
}
return pReverseHead;
}
把链表的构造给忘记了。。。。。。。。。。。。。。。好好检讨一下
有序链表合并
LinkNode* Merge(LinkNode* pHead1,LinkNode* pHead2)
{
if(pHead1==NULL)
return pHead2;
if(pHead2==NULL)
return pHead1;
LinkNode* pMergeHead=NULL;
if(pHead1->data>pHead2->data)
{
pMergeHead=pHead1;
pMergeHead->next=Merge(pHead1->next,pHead2);
}
else
{
pMergeHead=pHead2;
pMergeHead->next=Merge(pHead1,pHead2->next);
}
return pMergeHead;
}