单线性链表的创建,遍历以及增删查改

本文通过C++代码展示了如何创建、遍历、获取、插入和删除线性链表中的元素。首先定义了链表节点结构,然后实现了创建链表、打印链表、获取指定位置元素、在指定位置插入元素和删除指定位置元素的函数。在主函数中,进行了具体的操作演示。
摘要由CSDN通过智能技术生成
#include<iostream>
using namespace std;

typedef int datatype;

typedef struct LNode
{
	datatype data;
	struct LNode *next;

}LNode,*linklist;





//创建顺序链表
void createLinklist(linklist &ll,int n)//ll为指针变量?
{
	ll=(LNode *)malloc(sizeof(LNode));
	LNode *p,*L;
	L=ll;

	for(int i=1;i<=n;i++)
	{
		p=(LNode*)malloc(sizeof(LNode));
		cin>>p->data;
		L->next=p;
		L=p;
	}
	L->next=NULL;
}
//打印链表
void printList(LNode *head)
{
	LNode *p;
	p=head;
	while(p->next!=NULL)
	{
		p=p->next;
		cout<<p->data<<endl;
		
	}
}
//返回第index个元素给e,index从1开始,空头节点占据一个
int getElem(LNode *head,int index,datatype &e)
{
	LNode *p=(LNode *)malloc(sizeof(LNode));
	p=head;
	int j=0;
	while(p->next!=NULL&&j<index)
	{
		p=p->next;
		j++;
		
	}

	if(j<index)
	{
		cout<<"输入查询位置超出链表长度"<<endl;
		return 0;
	}
		e=p->data;
		return 1;
}
//在链表的第index个位置插元素e,index从1开始
int insertElem(LNode *head,int index,datatype e)
{
	LNode *p,*insertNode,*pbefor;
	insertNode=(LNode *)malloc(sizeof(LNode));
	insertNode->data=e;
	//p=(LNode *)malloc(sizeof(LNode));
	int j=0;
	p=head;
	pbefor=p;//p的前一个节点
	while(p->next!=NULL&&j<index)
	{
		pbefor=p;
		j++;
		p=p->next;
	}
	if(j<index-1)
	{
		cout<<"插入位置超出链表长度范围"<<endl;
		return 0;
	}



	主要是为了解决插入第一个元素存在的bug
	if(j==0)
	{
		p=p->next;
	}


	//这样可以在链表末尾插入元素
	if(p->next==NULL)
	{
		p->next=insertNode;
		insertNode->next=NULL;
		return 1;
	}


	pbefor->next=insertNode;
	insertNode->next=p;
	return 1;

}

//链表删除指定位置的元素,位置index从1开始
//但是如果表头是空固定不变的话,则没有这个bug
int delElem(LNode *head,int index)
{
	LNode *p,*pbefor;
	p=head;
	int j=0;
	while(p->next!=NULL&&j<index)
	{
		pbefor=p;
		j++;
		p=p->next;

	}
	if(j<index-1)
	{
		cout<<"删除位置越界"<<endl;
		return 0;
	}
	
	pbefor->next=p->next;

}
void main()
{
	LNode *head,*p;
	datatype e;
	createLinklist(head,5);
	printList(head);
	getElem(head,5,e);
	cout<<e<<endl;
	cout<<""<<endl;
	cout<<""<<endl;
	cout<<""<<endl;
	insertElem(head,6,33);
	printList(head);
	cout<<""<<endl;
	cout<<""<<endl;
	cout<<""<<endl;
	delElem(head,6);
	printList(head);
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值