这几天在学习链表,头一次学没什么经验,看看我的代码吧:
首先定第一个结构体存储链表的每个结点
struct node {
int data;
struct node *next;
};
然后去创建一些需要用到的节点变量
struct node *head,*p,*q,*t,*temp;//head为头节点,怕,p,q,t,temp.都为需要用到的临时变量
接下来写建立链表的create方法
void create(int n){
int a;
head=NULL;
for(int i=0;i<n;i++){
cin>>a;//输入值
p=(struct node *)malloc(sizeof(struct node));//分配空间
p->data=a;//给临时变量分配值
p->next=NULL;//将临时变量的后继指针设为空
if(head==NULL){
head=p;
}else{
q->next=p;
}
q=p;
}
}
写改变链表中值的方法change
void change(int a,int b){//接受要改变的值即将所有的a改为b
t=head;
while(t!=NULL){//从头开始遍历
if(t->data==a){//找到与a相等的结点
t->data=b;//将b赋给这个结点的tata
}
t=t->next;
}
}
删除的方法delet 写代码的时候主要是卡在了判断是否为头节点与尾节点的情况
void delet(int a){
t=head;
int i=1;
if(a==1){//判断是不是头节点
head=head->next;
free(t);
}else{
while(t->next!=NULL&&i<a-1){
t=t->next;
i++;
}
if(t->next==NULL){//判断是不是最后一个结点
t=NULL;
free(t);
}else{
temp=t->next;
t->next=temp->next;
free(temp);
}
}
}
遍历链表的show方法
void show(){
t=head;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}cout<<endl;
}
main方法
int main(){
int n;
cout<<"请输入要插入值的个数"<<endl;
scanf("%d",&n);
create(n);
show();
cout<<"请输入小替换的数字与替换的值"<<endl;
int b,cha;
cin>>b>>cha;
change(b,cha);
show();
cout<<"请输入要删除的位置"<<endl;
int d;
cin>>d;
delet(d);
show();
return 0;
}