C++类写链表

2020-04-16 15:44:42 浏览数 (1)

贝祖定理,当且仅当 z 是 x, y 的最大公约数的倍数时,ax by=z 有解

Class

C 中使用关键字 class 来定义类, 其基本形式如下:

代码语言:javascript复制
class 类名
{
    public:
    //行为或属性 
    protected:
    //行为或属性
    private:
    //行为或属性
};
 
实现代码:
class Point
{
    public:
         void setPoint(int x, int y);
         void printPoint();
 
    private:
         int xPos;
         int yPos;
};
代码语言:javascript复制
class linklist
{
    private:
        struct node
        {
            int data;
            node *next;
        }*p;
    public:
        linklist();
        void append(int num);
        void add_as_first(int num);
        void addafter(int c,int num);
        void del(int num);
        void display();
        int count();
        ~linklist();
};
linklist::linklist()
{
    p = NULL;
}
void linklist::append(int num)
{
    node *q,*t;
    if(p == NULL)
    {
        p = new node;
        p->data = num;
        p->next = NULL;
    }
    else
    {
        q = p;
        while(q->next!=NULL)
            q = q->next;
        t = new node;
        t->data = num;
        t->next = NULL;
        q->next = t;
    }
}
void linklist::add_as_first(int num)
{
    node * q;
    q = new node;
    q->data = num;
    q->next = p;
    p = q;
}
void linklist::addafter(int c,int num)
{
    node *q,*t;
    int i;
    for(int i =0;q = p;  i)
    {
        q = q->next;
        if(q ==NULL)
        {
            cout<<"nThere are less than"<<c<<"element";
            return ;
        }
    }
    t = new node;
    t->data = num;
    t->next = q->next;
    q->next = t;
}
void linklist::del(int num)
{
    node *q,*r;
    q = p;
    if(q->data == num)
    {
        p = q->next;
        delete q;
        return ;
    } 
    r = q;
    while(q!=NULL)
    {
        if(q->data == num)
        {
            r->next = q->next;
            delete q;
            return ;
        }
        r = q;
        q = q->next;
    }
    cout<<"nElement "<<num<<" not found";

}
void linklist::display()
{
    node *q;
    cout<<endl;
    for(q = p;q!=NULL;q=q->next)
    {
        cout<<endl<<q->data;
    }
}
int linklist::count()
{
    node * q;
    int c = 0;
    for(q = p;q!=NULL;q = q->next)
    {
        c  ;
    }
    return c;
}
linklist::~linklist()
{
    node *q;
    if(p == NULL)
        return ;
    while(p!=NULL)
    {
        q = p->next;
        delete p;
        p = q;
    }
}

0 人点赞