链表的颠倒算法

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值