问题:
1.建立一个带头结点的单链表,结点的值域为整型数据。要求将用户输入的数据按尾插入法来建立相应单链表。
2.设计一个函数在链表中查找元素x的位置,如果x不在链表中则返回-1。
3.设计一个函数将元素x插入第i个元素的后面。如果i大于链表的长度,则将x插入链表的末尾;如果i小于或等于0,则将x直接插入表头之后。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdlib>
#include<cmath>
#include<vector>
#define inf 0x3f3f3f3f
#define LL long long
const int mod = 1e9 + 7;
using namespace std;
typedef struct node
{
int data;
struct node *next;
} node,*Linklist;
//尾插法创建单链表
void creatlist(Linklist &l,int n)
{
node *p,*r;
l =new node;
l->next=NULL;
r=l;
cout<<"请输入要插入的数据:";
for(int i=0; i<n; i++)
{
p=new node;
cin>>p->data;
p->next=NULL;
r->next=p;
r=p;
}
}
//输出单链表
void outlinklist(Linklist l)
{
cout<<"此时单链表数据为:";
node *p;
p=l->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
//按值查找
int locatnumlist(Linklist l,int e)
{
node *p;
int flag=0;//记录下标
p=l->next;
while(p&&p->data!=e)
{
p=p->next;
flag++;
}
if(p==NULL)
return -1;
else
return flag;
}
//插入元素x
void LinkInsert(Linklist &l,int i,int e)
{
node *p,*s;
int j=0;
p=l;
while(p&&(j<i-1))
{
p=p->next;
++j;
}
if(!p)//插入到结尾
{
s=new node;
s=p->next;
s->data=e;
s=NULL;
}
else if(j>i-1)//插入到开头
{
s=new node;
s->next=l->next;
l->next=s;
s->data=e;
}
else
{
s=new node;
s->data=e;
s->next=p->next;
p->next=s;
}
}
int main()
{
Linklist la;
int n,m;
cout<<"请输入链表的长度:";
cin>>n;
creatlist(la,n);
outlinklist(la);
cout<<"输入要查找的值:";
cin>>m;
int sum=locatnumlist(la,m);
cout<<"查找结果:";
cout<<sum<<endl;
int s,num;
cout<<"要插入的位置和值";
cin>>s>>num;
LinkInsert(la,s,num);
outlinklist(la);
return 0;
}