链表的颠倒算法

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

点赞