链表面试题详解

本文详细介绍了单链表的基本操作,包括初始化、查找、插入、显示、反转、删除及合并等,并提供了完整的C++实现代码。此外,还讨论了如何判断链表中是否存在环以及如何创建带环的链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值