当前位置: 代码迷 >> 综合 >> 详细的单链表基本操作C/C++实现
  详细解决方案

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

热度:49   发布时间:2024-01-15 17:24:01.0
#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<<" ";//}
}

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

相对详尽。

  相关解决方案