每个函数都比较简单,关键是要注意判断结点是否为空,搞清楚指针域的指向(改变->next时的次序,防止丢失;在删除操作时创建临时结点pre记录上一个结点)
自己在《笔法笔记》的基础上做了一些完善和必要的注释,并加了display操作输出当前链表
主函数加了while{}和case分支,显得更加清晰、可交互,可见示例
注意 delete是C++的保留字,因此编写删除操作时要注意命名的问题
注意 使用new和delete(malloc和free作为库函数无法让结构体自动执行析构函数)
代码和示例如下
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node *next;
};
node* create(int Array[]){
node *p,*pre,*head;
head = new node;
head->next = NULL;
pre=head;
for(int i=0;i<5;i++){
p =new node;
p->data=Array[i];
p->next=NULL;
pre->next=p;
pre=p;
}
return head;
}
int search(node *head,int x){//返回链表中元素x的个数
int cnt=0;
node *p=head->next;
while(p!=NULL){
if(p->data==x){
cnt++;
}
p=p->next;
}
return cnt;
}
void insert(node *head,int pos,int x){//将x插入到第pos个位置上
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;
}
void del(node *head,int x){//删除值为x的元素
node *p=head->next;
node *pre=head;
bool flag=0;
while(p!=NULL){
if(p->data==x){
flag=1;//找到了x
pre->next=p->next;
delete(p);
p=pre->next;
}
else{
pre=p;
p=p->next;
}
}
if(!flag)cout<<"x not found!"<<'\n';
else cout<<"delete successfully"<<'\n';
}
void display(node *head){
node *p=head->next;
if(p!=NULL)
cout<<"display:"<<p->data;
p=p->next;
while(p!=NULL){
cout<<"->"<<p->data;
p=p->next;
}
cout<<'\n';
}
int main(){
int Array[100];
node *L=create(Array);
int op;
cout<<"enter 1 to create a list"<<'\n';
cout<<"enter 2 to get the total number of nodes whose value is x"<<'\n';
cout<<"enter 3 to insert a node whose value is x at position pos"<<'\n';
cout<<"enter 4 to delete all nodes whose value is x"<<'\n';
cout<<"enter 9 to exit"<<'\n';
do{
cout<<"please enter op:"<<'\n';
cin>>op;
switch(op){
case 1:{
cout<<"enter the total number of nodes"<<'\n';
int n;
cin>>n;
cout<<"enter the values of all nodes in turn"<<'\n';
for(int i=0;i<n;i++){
cin>>Array[i];
}
L=create(Array);
cout<<"create successfully!"<<'\n';
display(L);
}
break;
case 2:{
cout<<"enter x"<<'\n';
int x;
cin>>x;
cout<<"the total number of "<<x<<" is "<<search(L,x)<<'\n';
}
break;
case 3:{
int pos,x;
cout<<"enter pos and x"<<'\n';
cin>>pos>>x;
insert(L,pos,x);
display(L);
}
break;
case 4:{
int x;
cout<<"enter x"<<'\n';
cin>>x;
del(L,x);
display(L);
}
break;
}
}while(op!=9);
return 0;
}