您的位置:首页 > 职场人生

链表面试题详解

2016-06-07 19:07 387 查看
struct node
{
int value;
struct node *next;
node(int key=0):value(key){}
};
//无头的单链表
void init(node *&head)
{
if(NULL==head)
head=NULL;
}
//两种情况,head==NULL或者没有找到都返回NULL
//否则返回找到的节点
node* find(node *head,int key)
{
node *cur=head;
while(cur !=NULL && cur->value !=key)
cur=cur->next;
return cur;
}
void push_back(node *&head,int key)
{
if(head==NULL)
{
head=new node(key);
head->next=NULL;
}else
{
node *tmp=new node(key);
tmp->next=NULL;
node *cur=head;
while(cur->next !=NULL && cur->next->value !=key)
cur=cur->next;
tmp->next=cur->next;
cur->next=tmp;
}
}
void insert(node *&head,int key)
{
node *cur=find(head,key);
if(cur==NULL)//会出现head==NULL或者没有找到
push_back(head,key);
else
{
node *tmp=new node(key);
tmp->next=NULL;
tmp->next=cur->next;
cur->next=tmp;
}
}
void show(node *head)
{
node *cur=head;
while(cur !=NULL)
{
cout<<cur->value<<" ";
cur=cur->next;
}
cout<<endl;
}
//翻转
void reserve(node *&head)
{
node *cur=head;
head=NULL;
while(cur !=NULL)
{
node *tmp=cur;
cur=cur->next;
//
tmp->next=head;
head=tmp;
}
}
//删除
bool remove(node *&head,int key)
{
if(head==NULL)
return false;
if(head->value==key)
{
if(head->next==NULL)
{
delete head;
head=NULL;
}else
{
node *del=head;
head=head->next;
delete del;
del=NULL;
}
return true;
}
///接下来就key就不会和head->value相等,所以就可以从head->next->value开始比较
node *cur=head;
while(cur->next !=NULL && cur->next->value !=key)
cur=cur->next;
if(cur->next==NULL)
return false;
node *del=cur->next;
cur->next=del->next;
delete del;
del=NULL;
return true;
}
//合并两个有序链表
node* merger(node *&des,node *&src)
{
if(des==NULL)
return src;
if(src==NULL)
return des;
node *head=new node(0);
node *cur=head;

while(des !=NULL && src !=NULL)
{
if(des->value >src->value)
{
cur->next=src;
src=src->next;
}
else
{
cur->next=des;
des=des->next;
}
cur=cur->next;
}
if(des==NULL)
cur->next=src;
else
cur->next=des;
cur=head->next;
delete head;
head=NULL;
return cur;
}
//判断是否有环
bool IsRing(node *head)
{
if(head==NULL || head->next==NULL)
return false;
node *fast=head;
node *slow=head;
while(fast !=NULL && fast->next !=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}
//创建有环链表,并实现头插
void create_ring(node *&head,int key)
{
if(head==NULL)
{
head=new node(key);
head->next=head;
}else
{
node *tmp=new node(key);
node *cur=head;
while(cur->next !=head)
cur=cur->next;
tmp->next=cur->next;
cur->next=tmp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单链表 C++