链表一系列经典问题
作者:互联网
1.删除指定结点
#include<stdio.h>//删除指定节点
#include<stdlib.h>
int key;
struct Node{
int a;
struct Node *next;
};
struct Node* Build(){
struct Node *view,*head,*rear,*p;//易错点1:各个指针要在前面加*,不能 struct Node *view,head,rear,p
view=(struct Node*)malloc(sizeof(struct Node));
view->next=0;
head=view;
rear=view;
while(1){
p=(struct Node*)malloc(sizeof(struct Node));
p->next=0;//创一个一定要指向0
scanf("%d",&p->a);
if(p->a==0) break;
rear->next=p;
rear=p; //错点2:是 rear=p而不是p=rear
}
return head->next;}
struct Node* Delete(struct Node* head){
struct Node* p0,*preturn;
preturn=head;
if(head->a==key){
head=head->next;
return head;
}else{
while(head!=0 && head->a!=key){ //head是要删掉的
p0=head;
head=head->next;
}
if(head->next!=0)
p0->next=head->next;
else
p0->next=0;
}
return preturn;}
void Daying(struct Node* head){
while(head!=0){
printf("%d ",head->a);
head=head->next;
}
}
int main(){
struct Node* head;
scanf("%d",&key);
head=Build();
//printf("%d\n",head->a);
head=Delete(head); //修改并存入
Daying(head);
return 0;
}
2.按学号插入(需要用到尾插,头插,中插,按下一个节点的数据不同分类)
#include<stdio.h> //按学号排序打出来,在built插入
#include<stdlib.h>
int flag=1; //为第一次的tmp0什么赋值struct Node* head;
struct Node{
int a;
int score;
struct Node *next;
};
struct Node* Build(){
struct Node *view,*head,*rear,*p,*tmp,*tmp0;
view=(struct Node*)malloc(sizeof(struct Node));
view->next=0;
view->a=-1000;//方便第一次进入循环
head=view;
rear=view;
while(1){
tmp=head; //每一次都从哨兵开始寻找遍历
p=(struct Node*)malloc(sizeof(struct Node));
p->next=0;//创一个一定要指向0
scanf("%d %d",&p->a,&p->score);
if(p->a==0) break;
//链接部分要好好考虑了
if(tmp->next!=0){
if(p->a < tmp->next->a){ //比第一个小,头插
p->next=tmp->next;
tmp->next=p;
}else{
while((tmp->next!=0) && (p->a > tmp->a )) //
{//出循环说明此时的p比tmp的a小,比tmp0的a大,或者tmp是最后一位了
tmp0=tmp;
tmp=tmp->next;
}
if(tmp->next==NULL) //如果是最后一个
{
tmp->next=p;
p->next=0;
}
else
{
tmp0->next=p;
p->next=tmp;
}
}
}
else//如果位于最后了直接连上去,先录入第一个
{
tmp->next=p;
p->next=0;
}
}
return head;}
void daying(struct Node* head){
while(head!=0){
printf("%d ",head->score);
head=head->next;
}
}
int main(){
struct Node* head;
head=Build();
daying(head->next);
return 0;
}
标签:Node,tmp,head,struct,next,链表,经典,view,一系列 来源: https://blog.csdn.net/weixin_50382279/article/details/111845928