#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct Node node;
struct Node
{
long long int data;
node *last,*next;
};
node *createnode(long long int n)
{
node *nodes[n];
long long int i;
for(i=0;i<n;i++)
{
nodes[i]=(node*)malloc(sizeof(node));
nodes[i]->last=(node*)malloc(sizeof(node));
nodes[i]->next=(node*)malloc(sizeof(node));
}
for(i=0;i<n;i++)
{
nodes[i]->data=i;
nodes[i%n]->next=nodes[(i+1)%n];
nodes[(i+1)%n]->last=nodes[i];
}
return nodes[0];
}
node *atnode(node* first,long int data)
{
node *current5;
current5=first;
while(current5->data!=data)
{
current5=current5->next;
}
return current5;
}
void deletenode(node *first,int data)
{
node *current2;
current2=atnode(first,data);
current2->last->next=current2->next;
current2->next->last=current2->last;
current2->next=NULL;
current2->last=NULL;
return;
}
void finsertnode(node *first,long int a,long int b)
{
deletenode(first,a);
node *newnode=(node*)malloc(sizeof(node)),*current3=atnode(first,b);
newnode->data=a;
current3->next->last=newnode;
newnode->next=current3->next;
current3->next=newnode;
newnode->last=current3;
return;
}
void rinsertnode(node *first,long int a,long int b)
{
deletenode(first,a);
node *newnode,*current4=atnode(first,b);
newnode->data=a;
current4->last->next=newnode;
newnode->last=current4->last;
current4->last=newnode;
newnode->next=current4;
return;
}
int main()
{
long long int n,a,b;
int m,q,i;
cin>>n;
cin>>m;
cin>>q;
cin.ignore();
node *first=createnode(n),*current;
char com[q];
long long int arra[q],arrb[q];
for(i=0;i<q;i++)
{
cin>>com[i];
cin>>arra[i];
cin>>arrb[i];
if(com[i]=='F')
{
finsertnode(first,arra[i],arrb[i]);
continue;
}
if(com[i]=='R')
{
rinsertnode(first,arra[i],arrb[i]);
continue;
}
}
int arr[q];
for(i=0;i<q;i++)
{
cin>>arr[i];
}
for(i=0;i<q;i++)
{
current=(node *)malloc(sizeof(node));
current=atnode(first,arr[i]);
cout<<current->last->data<<' '<<current->next->data<<' ';
}
return 0;
}
用 codeblock能執行,但測試執行沒過,求解?
你 code 中的
node *nodes[n];
node *current5;
等等都是 stack memory 離開 function 記憶體就被釋放
改用 heap memory
眼殘沒看到有用malloc 丟臉><
更正一下,在
這裡的 *newnode 沒有配置記憶體就使用
還有你malloc 後都沒有free
這裡的第一個for 迴圈中的這兩行記憶體配置沒有用到
被第2個迴圈中的這兩行給覆蓋
造成memory leak