创建有n个元素的链表,链表的元素的添加,链表元素的删除,链表的输出。
声明结构类型和主函数
#include<bits/stdc++.h>
using namespace std;
node *creat(int n);//创建有个n个结点的单链表
node *insert(node *h,int m,int l);//在单链表的第几个元素之后插入值l
node *remove(node *h,int t,int n);//删除链表中值为t的元素
void show(node *h);//输出n个结点的单链表
struct node
{
int data;
node *next;
};
int n,m,l,t;//n为链表结点的个数,m是在链表第几个之后插入元素l,t为要删除的链表中相同的元素
int main()
{
node *head;//创建头结点
cin>>n;
head=creat(n);//创建有n个元素的链表
show(head);//输出
cout<<endl;
cin>>m>>l;
head=insert(head,m,l);//插入
show(head);
cin>>t;
head=remove(head,t,n+1);//删除
show(head);
}
链表的创建
node *creat(int n)
{
node *h,*p;
h=new node;//建立第一个结点
p=h;
for(int i=1;i<=n;i++)
{
cin>>p->data;//向结点赋值
if(i<n)//建立后续结点
{
p->next=new node;
p=p->next;
}
}
p->next=h;//构成链环
return h;
}
图片演示
链表的输出
void show(node *h)//输出n个结点的单链表
{
node *p;
p=h;
do{
cout<<p->data<<" ";
p=p->next;
}while(p!=h);
}
链表的插入
node *insert(node *h,int m,int l)//在单链表的第几个元素之后插入链表
{
node *p,*s;
int i=0;//用来判断位置
p=h;
s=new node;
do{
i++;
if(i==m)
{
s->next=p->next;
p->next=s;
s->data=l;
}
else p=p->next;
}while(p!=h);
return h;
}
链表中的结点删除
node *remove(node *h,int t,int n)//删除链表中值为t的元素
{
int i=0;
node *p=h;
do
{
if(p->next->data==t)
{
p->next=p->next->next;//p所指向的下一个结点被赋值为下两个结点
if(i==n-1) return h->next;//判断是否是第一个元素 如果是直接不返回第一个结点
else return h;
}
else
{
p=p->next;//向后遍历
i++;
}
}while(p!=h);
}