//链式存储之单链表
#include<iostream>
using namespace std;
typedef int elemtype;//此处int可替换成别的数据类型
//创建节点
typedef struct node
{
elemtype data; //数据域
struct node *next; //指针域
}node,*listnode;
/*
此处需要注意
1. listnode ln; ln是单链表的头指针 **节点变量**
2. node *p; *p是指向单链表中某个节点的指针 **指针变量**
*/
//1.单链表的初始化
/*
步骤:
1.生成新节点作为头节点,用头指针l指向头节点
2.头节点的指针域=null
*/
bool newlist(listnode &l)
{
l=new node;
l->next=NULL;//NULL 需要全部大写
return true;
}
//单链表的取值
/*
步骤:
1.指针p指向首元节点,计数器j=1;(首元节点是第一个存储数据的节点)
2.从首元节点开始顺着*next向下访问
3.只要p!=NULL且未到达第i个位置(j<i)就循环执行以下操作
a.p指向下一个节点
b.j++
4.退出循环时,如果指针p为空||j>i,说明i的值不合法,返回false
5.如果j==i,则返回e=p->data
*/
bool getelem(listnode l,int i,elemtype &e)
{
node *p=l->next;//指向首元节点
int j=1;
while(p&&j<i)
{
p=p->next;
++j;
}
if(!p||j>i)
{
return false;
}
e=p->data;
return true;
}
//单链表的查找
/*
步骤:
1.指针p指向首元节点
2.从首元节点顺着*next向下查找,只要p!=NULL&&P->data!=e
3.则循环一个操作:p=p->next;
4.返回p;如果查找成功,返回的是该节点的地址,如果失败,则为NULL
*/
node *locatElem(listnode l,elemtype e)
{
node *p=l->next;
while(p&&p->data!=e)
{
p=p->next;
}
return p;
}
//单链表的插入
/*
步骤:
1.查找第i-1个位置,指针p指向它
2.生成一个新节点*s
3.将新节点的数据域设为e
4.将新节点的指针域指向ai
5.将节点*p指向*s
*/
bool insert(listnode &l,int i,elemtype e)
{
node *p=l;
int j=0;
while(p&&j<i-1) //这里是p!=NULL
{
p=p->next ;
++j;
}
node *s=new node;
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
//单链表的删除
/*
步骤:
1.查找第i-1个位置,并用*p指向它
2.用*q临时保存待删除节点ai的地址
3.*p的指针域指向ai的直接后继点
4.释放ai的空间
*/
bool deletenode(listnode &l,int i)
{
node *p=l;
int j=0;
while ((p->next)&&(j<i-1)) //这里是p->!=NULL
{
p=p->next;
++j;
}
if(!(p->next)||(j>i-1))
return false;
node *q=p->next;
p->next=q->next;
delete q;
return true;
}
//前插和后插建立单链表
//前插法
/*
步骤:
1. 创建一个只有头节点的空链表
2.根据创建链表包括的元素总数n,循环n次
a.生成一个新节点*p
b.输入元素并赋值给*p的数据域
c.将新节点*p插入头节点之后
(注意这里插入顺序和逻辑顺序相反)
*/
void headinsert(listnode &l, int n)
{
l=new node;
l->next=NULL;
for(int i=0;i<n;i++)
{
node *p=new node;
cin>>p->data;
p->next=l->next;l->next=p;//将新节点*p插入到头节点之后
}
}
//后插法
/*
步骤:
1.创建一个只有头节点的空链表
2.初始化尾指针*r,指它指向头节点
3.根据元素数n,循环n次
a.生成一个新节点*P
b.输入元素并赋值给*p的数据域
c.将新节点*p插入到尾节点*r之后
d.尾指针r指向尾节点*P
(后插法元素插入顺序与逻辑顺序相同)
*/
void backnode(listnode &l,int n)
{
l=new node;
l->next=NULL;
node *r=l;
for(int i=0;i<n;i++)
{
node *p=new node;
cin>>p->data;
p->next=NULL;
r->next=p;
r=p;
}
}
int main()
{
return 0;
}
来源:https://blog.csdn.net/qq_43570024/article/details/100541280