单链表的复制、深拷贝

本文通过C++代码示例介绍了如何实现单链表的创建、插入操作及复制过程。具体包括定义链表结构体、初始化链表、在指定位置插入节点以及复制整个链表的方法。

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

用C++写了几个函数,一个小例子来表示单链表的复制过程

//创建链表
struct node
{
	int data;
	node* next;

};
typedef node linklist;
linklist *initLinklist()
{
	linklist *first;
	node *l=new node;
	l->data=1;
	l->next=NULL;
	first=l;
	return first;
}
//在链表第i个节点处插入
bool insertLinklist(linklist* &l,node *p,int i)
{
	int n=0;
	linklist *temp=l;//临时指针
	if(0==i)
	{
		p->next=l;
		l=p;
		cout<<"插入成功";
		return true;
	}
	int count=1;
	while(temp)
	{
		
		if(count==i)
		{
			p->next=temp;
			temp=p;
			cout<<"插入成功";
			return true;
		}
			temp=temp->next;	
			count++;
	}	
	return false;
}
//复制链表
linklist* copyLinklist(linklist *l,linklist *cl)
{
	
	linklist *temp=l;//临时指针,取l的值
	
	linklist *ctemp;
	
	if(l)
	{	//先记录头节点位置
		node *cnode=new node;//临时节点,接受temp的值
		cnode->data=temp->data;
                cnode->next=NULL;
		temp=temp->next;
		
		cl=cnode;
		cout<<"copy"<<cl->data;
		ctemp=cl;
		
        while(temp)
		{
		
			node *cnode=new node;//临时节点,接受temp的值
			cnode->data=temp->data;
                        cnode->next=NULL;
			temp=temp->next;
		
			//将临时节点插入到链表;
			ctemp->next=cnode;
			ctemp=cnode;
			cout<<"插入成功";
		}

	}
	else
		cl=NULL;
	
	return cl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	node *p;
	p=new node;
	p->data=2;
	p->next=NULL;
	linklist* l=initLinklist();
	cout<<l->data;
	insertLinklist(l,p,0);
	cout<<l->data;
	linklist *cl=new linklist;
	cl=copyLinklist(l,cl);
	cout<<"复制后";
	cout<<cl->data;
	cout<<cl->next->data;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值