-4
以下是通用链接列表的代码。代码不起作用。无法弄清楚什么是错的。没有编译错误,但没有输出。通用C++链接列表
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Node{
void* data;
Node* next;
};
void Insert(Node** head,void* k,size_t data_size){
Node* temp=(Node*)malloc(sizeof(Node));
temp->data=malloc(data_size);
temp->next=*head;
for(int i=0;i<data_size;i++){
*((char*)(temp->data) + i) = *((char*)(k)+ i);
}
*head=temp;
}
void PrintList(Node* head,void (*fptr)(void*)){
Node* temp=head;
while(temp!=NULL){
(*fptr)(temp->data);
temp=temp->next;
}
}
void PrintInteger(void* k){
printf("%d",*(int*)(k));
}
void PrintFloat(void* k){
printf("%f",*(float*)k);
}
int main(){
int a[]={4,1,9,5};
float b[]={1.3,7.6,2.5,4.7};
Node*head=NULL;
unsigned int_size=sizeof(int);
unsigned float_size=sizeof(float);
for(int i=3;i>=0;i++){
Insert(&head,&a[i],int_size);
}
PrintList(head,PrintInteger);
cout<<endl;
Node* head2=NULL;
for(int i=3;i>=0;i++){
Insert(&head2,&b[i],float_size);
}
PrintList(head2,PrintFloat);
}
看起来不像'PrintList'打印什么... – evsheino
环路在'Insert'中可以用对'memcpy()'的调用来替换。 – Barmar
@evsheino它调用'fptr'回调,它打印元素。 – Barmar