#include<iostream>
#include<algorithm>
using namespace std;
//结构体
struct node{
int data;
node *next;
};
//创建链表
node* create(int arry[]){
node *p,*pre,*head;
head=new node;//创建头结点
head->next=NULL;//初始化头结点
pre=head;
for(int i=0;i<5;i++){
p=new node;//新建结点
//cin>>i;
p->data=arry[i];
p->next=NULL;
pre->next=p;
pre=p;//pre设为p,下个结点的前去结点
}
return head;//返回头结点指针
}
//查找元素
//查找值为x的元素个数
int search(node *head,int x){
int count=0;
node *p=head->next;
while(p!=NULL){
if(p->data==x){
count++;
}
p=p->next;
}
return count;
}
//在指定位置插入元素
void insert(node *head,int pos,int x){
node*p=head;
for(int i=0;i<pos-1;i++){//找到插入位置的前一个结点
p=p->next;
}
node *q=new node;//新建结点
q->data=x;
q->next=p->next;
p->next=q;
}
//删除链表上所有值为给定X
void del(node *head,int x){
node *p=head->next;
node *pre=head;//前驱
while(p!=NULL){
if(p->data==x){
pre->next=p->next;
delete(p);
p=pre->next;
}
else{
pre=p;
p=p->next;
}
}
}
int main(){
int Arry[5]={5,3,6,1,2};
node *L=create(Arry);//新建链表,返回的头指针head赋值给L
/* 测试输出链表。建立完链表可进行输出、查找,测试链表是否建立成功
L=L->next;//第一个有数据的结点
while(L!=NULL){
cout<<L->data<<" ";
L=L->next;
}
*/
//查找元素x 返回链表里x的个数
//cout<<search(L,3);
insert(L,3,3);//插入
del(L,5);//删除
L=L->next;//第一个有数据的结点
while(L!=NULL){
cout<<L->data<<" ";
L=L->next;
}
cout<<endl;
return 0;
}