注册 登录
编程论坛 C++教室

一个简单的链表 程序运行不出

dtxwz 发布于 2017-04-13 21:26, 2076 次点击
#include<iostream.h>

struct data
{
    int value;
    data *next;
};
class Memory
{
public:
    data *head;
    Memory(){head = head->next = NULL;}
    data* mallo(int n);
    void fre(data *h);
    void print(data *h,int n);
};
data* Memory::mallo (int n)      //实现malloc函数
{
    int i = 0;
    data *t = NULL;
    if(n<0)cout<<"error"<<endl;
    while(i<n)
    {
        if(head==NULL)
        {
            head = new data;
            t = head;
            head->value = i;
            
            i++;
        }
        else
        {
            head->next = new data;
            head = head->next;
            head->value = i;
            i++;
        }
    }
    head->next = NULL;
    return t;
}

void Memory::print(data *h,int n)  
{
    int i;
    for(i = 0;i < n-1;i++)
    {
        h = h->next ;
    }
    cout<<h->value<<endl;
}
void Memory::fre (data *h)
{
    data *t = h;
    while(h)
    {
        t = h->next ;
        delete h;
        h = t ;
    }
}
int main()
{
    Memory a;
    data *t;
    t = a.mallo (5);
    a.print(t,4);
    return 0;
}
4 回复
#2
rjsp2017-04-14 08:32
代码当然是错得一无是处,但这是小事。
大事是,你连你要写出什么功能都不知道?看看你的调用代码
int main()
{
    Memory a;
    data *t;
    t = a.mallo (5);
    a.print(t,4);
    return 0;
}
#3
dtxwz2017-04-14 10:00
回复 2楼 rjsp
功能就是模拟malloc函数啊
#4
yangfrancis2017-04-14 18:29
先new. 再传给next指针
#5
yangfrancis2017-04-14 18:33
先new. 再传给next指针
1