1. 实现atoi函数
2. 实现node * reverse(node * head)翻转链表
上面提到的这两道题是在www.cppblog.com/yearner/archive/2008/05/29/51515.html看到的
由于这个是面试时的笔试题,所以相对真正的笔试题来说是比较简单点
下面给出我的写的答案,有什么不对的地方,望各位指出。。。
#include <cstdlib>
#include <iostream>
using namespace std;
//atoi
int myatoi(const char* str)
{
assert(str);
while(*str==' ')str++;
char c=*str++;
if(c!='-'&&(c<'0'||c>'9'))return 0;
bool negative=false;
int total=0;
if(c=='-'||c=='+')
{
if(c=='-')
negative=true;
c=*str++;
}
while(c)
{
if(c>='0'&&c<='9')
{
total=total*10+(c-'0');
c=*str++;
}
else break;
}
return negative?-total:total;
};
//reverse 有关部分
struct node //节点
{
int k;
node *next;
};
node * reverse(node * head) //翻转
{
if(!head)return NULL;
node*p=NULL,*q=NULL,*r=NULL;
p=head->next;
if(p)
{
q=p->next;
p->next=NULL;
}
if(q)
r=q->next;
while(q)
{
q->next=p;
p=q;
q=r;
if(r)
r=r->next;
}
head->next=p;
return head;
};
void showlist(node*head) //列举
{
node*p=head->next;
while(p)
{
cout<<p->k<<endl;
p=p->next;
}
};
int main(int argc, char *argv[])
{
//使用atoi转换
cout<<myatoi("-1233454abc")<<endl;
//使用reverse翻转
node *head=new node;
head->next=NULL;
node *p=head;
node *newnode;
for(int i=0;i<5;i++)
{
newnode=new node;
newnode->k=i;
newnode->next=NULL;
p->next=newnode;
p=newnode;
}
newnode=NULL;
head=reverse(head);
showlist(head);
//释放资源
while(head)
{
newnode=head;
head=head->next;
delete newnode;
}
system("PAUSE");
return EXIT_SUCCESS;
}