求助
  • 板块学术版
  • 楼主Laihaocheng
  • 当前回复0
  • 已保存回复0
  • 发布时间2025/1/20 20:30
  • 上次更新2025/1/20 22:35:55
查看原帖
求助
1069294
Laihaocheng楼主2025/1/20 20:30

本蒟蒻初学链表,不清楚47-52行作用,请佬解答,玄2小号关

#include <bits/stdc++.h>
using namespace std;
struct node{
	int data;
	node *next;
};
node *head=NULL;
void add(int x){
	if(head!=NULL){
		node *a=new node;
		a->data=x;
		a->next=NULL;
		node *p=head;
		while(p->next!=NULL) p=p->next;
		p->next=a;
	}else{
		head=new node;
		head->data=x;
		head->next=NULL;
	}
}
void insert(int n,int x){
	node *d=new node;
	d->data=x;
	d->next=NULL;
	if(n==1){
		d->next=head;
		head=d;
	}else{
		node *p=head;
		for(int i=1;i<=n-2;i++){
			p=p->next;
			if(p==NULL) break;
		}
		if(p==NULL) printf("nÓÐÎó\n");
		else{
			d->next=p->next;
			p->next=d;
		}
	}
}
void deldata(int data){
	node *p=head,*pre=NULL;
	while(p!=NULL){
		if(data==p->data){
			if(p==head) head=p->next;
			else pre->next=p->next;//
			delete p;//
			break;
		}
		pre=p;//
		p=p->next;//
	}
}
void delpos(int n){
	node *p=head;
	if(n==1){
		if(head!=NULL){
			head=head->next;
			delete p;
		}else printf("Á´±í¿Õ\n");
	}else{
		for(int i=1;i<=n-2;i++){
			p=p->next;
			if(p==NULL) break;
		}
		if(p==NULL||p->next==NULL) printf("nµÄÖµÓÐÎó£¡\n");
		else{
			node *t=p->next;
			p->next=t->next;
			delete t;
		}
	}
}
void display(){
	node *p=head;
	while(p!=NULL){
		printf("%d ",p->data);
		p=p->next;
	}
	puts("");
}
int main(){
	printf("ÇëÊäÈëÖ¸Á1.×·¼Ó£¬2.²åÈ룬3.ɾ³ýÖµ£¬4.ɾ³ýλÖã¬5.ÏÔʾ\n");
	while(true){
		int order;
		scanf("%d",&order);
		if(order==1){
			int x;
			scanf("%d",&x);
			add(x);
		}else if(order==2){
			int p,x;
			scanf("%d%d",&p,&x);
			insert(p,x);
		}else if(order==3){
			int x;
			scanf("%d",&x);
			deldata(x);
			display();
		}else if(order==4){
			int x;
			scanf("%d",&x);
			delpos(x);
			display();
		}else{
			display();
		}
	}
	return 0;
}
2025/1/20 20:30
加载中...