链表的颠倒算法
2015-09-29 23:15
218 查看
NO.10
用一种算法来颠倒一个链接表的顺序。现在在不用递归式的情况下做一遍。[cpp] view plaincopy
include
using namespace std;
struct node
{
int x;
node *next;
node()
{
x = 0;
next = NULL;
};
};
void make(node *head)
{
node *hea = head;
for(int i = 0;i<10;i++)
{
node *x = new node;
x->x= i;
hea->next = x;
hea = x;
}
};
void reverse(node *&head)
{
if(head->next == NULL)
return;
node *x = head;
head = head->next;
x->next = NULL;
while(NULL !=head)
{
node *y = head;
head = head->next;
y->next = x;
x = y;
}
head = x;
int i ;
};
int main()
{
node *head = new node;
//head->x = 4;
make(head);
reverse(head);
return 0;
}
而用递归方法实现的过程是:
[cpp] view plaincopy
node* reverse2(node *oldhead,node *newhead = NULL )
{
node *next = oldhead->next;
oldhead->next = newhead;
newhead = oldhead;
return (NULL == next) ? newhead:reverse2(next,newhead);
};
(2) 颠倒一个字符串。优化速度。优化空间
[cpp] view plaincopy
void reverseChar(char *str)
{
char *start = str;
int n = strlen(str);
char *p = str+n-1;
while(start < p)
{
char c = *start;
*start = *p;
*p=c;
start++;
p–;
}
}
(3)找到一个子字符串。优化速度。优化空间。
利用的Sunday算法
[cpp] view plaincopy
int sunday(const char *src,const char *des)
{
int i,j,pos=0;
int len_s,len_d;
int next[26]={0}; //next数组,预处理初始化
len_s=strlen(src);
len_d=strlen(des);
for(j=0;j<26;++j) //初始化next数组
next[j]=len_d;
for(j=0;j
相关文章推荐
- [C/C++]反转链表
- 动易2006序列号破解算法公布
- C#实现基于链表的内存记事本实例
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#中的递归APS和CPS模式详解
- C#冒泡法排序算法实例分析
- WinForm实现按名称递归查找控件的方法
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- C#中的尾递归与Continuation详解
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法