详细的单链表基本操作C/C++实现

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
typedef struct snode									
{
	int data;
	struct snode *next;
}lnode;
int listinsert(lnode *l,int i,int e)					//结点插入指定位置
{
	lnode *p=l;
	int j=0;
	while(p&&j<i-1)									//查找指定位置
	{
		p=p->next;
		j++;
	}
	if(!p||j>i-1)									//如果不存在指定位置
	{
		cout<<"error!the location is illegal"<<endl;
		return 0;
	}
	lnode *s;										//动态分配一个结点
	s=(lnode *)malloc(sizeof(lnode *));
	s->data=e;
	s->next=p->next;
	p->next=s;
	return 1;
}
void creatlist(lnode *l,int n)						//建立指定结点个数的链表
{
	int i;
	lnode *p;
	//l=(lnode *)malloc(sizeof(lnode *));
	l->next=NULL;
	cout<<"please input the elements you want :"<<endl;
	while(n)
	{
		p=(lnode *)malloc(sizeof(lnode *));
		cin>>p->data;
		p->next=l->next;
		l->next=p;
		n--;
	}
}
int listdelete(lnode *l,int i,int &e)				//删除指定结点
{
	lnode *p,*q;
	int j=1;
	p=l;
	while(p&&j<=i-1)								//查找结点位置
	{
		p=p->next;
		j++;
	}
	//cout<<"j1="<<j<<endl;
	if(!p||j>i-1)								//如果指定位置不存在
	{
		cout<<"the NO."<<i<<"element is not exist"<<endl;
		getch();
		return 0;
	}
	//cout<<"j2="<<j<<endl;
	q=p->next;
	p->next=q->next;
	e=q->data;
	cout<<e;
	//free(q);
	return 0;
}
void main()
{
	int i,j,e;
	lnode *l,*p,*q;
	int listnodenum;
	/*int array1[11]={1,2,3,4,5,6,7,8,9,10};
	l=(lnode *)malloc(sizeof(lnode *));
	l->next=NULL;
	for(i=10;i>0;i--)
	{
		p=(lnode *)malloc(sizeof(lnode *));
		p->data=array1[i-1];
		p->next=l->next;
		l->next=p;
	}*/
	l=(lnode *)malloc(sizeof(lnode *));				//头结点
	int n;
	cout<<"please input the num of the elements:";
	cin>>n;
	creatlist(l,n);
	p=l;
	cout<<endl<<endl<<"the old lnode is:";
	while(p->next!=NULL)
	{
		p=p->next;
		cout<<p->data<<" ";
	}
	cout<<endl<<endl<<"please input the location to insert(1-11):";
	cin>>j;
	cout<<"please input the integer to insert:";
	cin>>e;
	if(listinsert(l,j,e))
	{
		cout<<endl<<"the new lnode is:";
		p=l;
		while(p->next!=NULL)
		{
			p=p->next;
			cout<<p->data<<" ";
		}
	}
	cout<<endl<<"input the num you want delete:";
	int num;
	cin>>num;
	listdelete(l,num,e);
	j=1;
	cout<<endl<<"the new lnode is:";
	p=l;
	while(p->next!=NULL)
	{
		p=p->next;
		cout<<p->data<<" ";
		++j;
	}
	//cout<<"l is"<<l->next->data<<endl;
	//p=l;
	//for(i=1;i<=11;i++)
	//{
	//	
	//	p=p->next;
	//	//cout<<p->data<<" ";
	//	if(i==num)
	//	{
	//		q=p->next;
	//		p->next=q->next;
	//		cout<<q->data<<endl;
	//		break;
	//	}
	//}
	//cout<<endl<<"the new lnode is:";
	//p=l;
	//for(i=0;i<10;i++)
	//{
	//	
	//	p=p->next;
	//	
	//	cout<<p->data<<" ";
	//}
}

总结:注释代码为某些功能为组织成函数时的代码样子。

相对详尽。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值