社区讨论

苯蒟蒻想问关于free的问题

P1160队列安排参与者 3已保存回复 2

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
2 条
当前快照
1 份
快照标识符
@lo2y0inz
此快照首次捕获于
2023/10/23 21:38
2 年前
此快照最后确认于
2023/10/23 21:38
2 年前
查看原帖
在函数内开定义一个指针,让他等于链表某个地址,然后我怕他占内存就把他free掉了,结果原列表里的指针也被free掉了???why 那两个free在back_in和front_in函数的最后一行(我把它注掉才过的。。。)
CPP
#include<iostream>
#include<algorithm>
//#include<cstring>
//#include<math.h>
//#include<queue>
#include<stdlib.h>
//#include<vector> 
//#include<stack>
using namespace std;
typedef struct _node{
	int value;
	struct _node *next;	
	struct _node *before;
}Node;
typedef struct _list{
	Node*head;
	Node*tail;
}List;
Node* arr[100010];
bool pd[100010];
void add(List*plist,int number){
	Node*p;
	p=(Node*)malloc(sizeof(Node));
	p->value=number;
	p->next=NULL;
	if(plist->head&&plist->tail){
		p->before=plist->tail;
		plist->tail->next=p;
		plist->tail=p;
	}
	else{
		p->before=NULL;
		plist->head=p;
		plist->tail=p;
	}
	arr[number]=p;
}
void front_in(List*plist,int number,int in)
{
	Node*q=arr[number];
	Node*p;
	p=(Node*)malloc(sizeof(Node));
	arr[in]=p;
	p->value=in;
	p->next=q;
	p->before=q->before;
	if(plist->head!=q){
		q->before->next=p;
	}
	else{
		plist->head=p;
	}
	q->before=p;
	//free(q);
}
void back_in(List*plist,int number,int in)
{
	Node*q=arr[number];
	Node*p;
	p=(Node*)malloc(sizeof(Node));
	arr[in]=p;
	p->value=in;
	p->before=q;
	p->next=q->next;
	if(q!=plist->tail){
		q->next->before=p;
	}
	else{
		plist->tail=p;
	}
	q->next=p;
	//free(q);
}
void del(List *plist,int number){
	Node*p=arr[number];
	if(p==plist->head){
		plist->head=p->next;
		p->next->before=NULL;
	}
	else if(p==plist->tail){
		plist->tail=p->before;
		p->before->next=NULL;
	} 
	else{
		p->before->next=p->next;
		p->next->before=p->before;
		free(p); 
	}
}
int main(){
	List list;
	list.head=NULL;
	list.tail=NULL;
	int n,who,f,m;
	cin>>n;
	add(&list,1);
	for(int i=2;i<=n;i++){
		cin>>who>>f;
		if(f==1) back_in(&list,who,i);
		else front_in(&list,who,i);
	}
	cin>>m;
	for(int i=1;i<=m;i++){
		cin>>who;
		if(pd[who]==0){
			del(&list,who);
			pd[who]=1; 
		}
	}
	Node*p;
	for(p=list.head;p;p=p->next){
		cout<<p->value<<' ';
	}
	return 0;
}

回复

2 条回复,欢迎继续交流。

正在加载回复...