C++链表封装

头文件  mylist.h

#ifndef MYLIST_H
#define MYLIST_H

typedef struct node
{
    int data; //数据域
    struct node *next; //指针域
}Node;

class mylist
{
public:
    mylist();
    ~mylist();
    void insertList(int data);
    Node * searchList(int find);
    void trverList();
private:
    Node * head;
};

#endif // MYLIST_H

函数体  mylist.cpp

#include "mylist.h"
#include <iostream>
#include <stdlib.h>
using namespace std;

mylist::mylist()//建立头节点
{
    head = new Node;
    head->next = NULL;
}

mylist ::~mylist() //析构器  删除
{
    Node *t = head;
    while(head)
    {
        head = head->next;
        delete t;
        t = head;
    }
}

void mylist::insertList(int data) //插入节点
{
    Node *cur = new Node;
    cur->data = data;
    cur->next = head->next;
    head->next = cur;
}

Node * mylist::searchList(int find)//查找  返回指针
{
    head = head->next;
    while(head)
    {
        if(head->data = find)
            return head;
        head = head->next;
    }
    return NULL;
}

void mylist::trverList() //遍历 输出节点内容
{
    Node * t = head->next;
    while(t)
    {
        cout<<t->data<<endl;
        t = t->next;
    }
}
//调用

#include <iostream>
#include "mylist.h"

using namespace std;

int main()
{
   mylist List;
   List.insertList(2);
   List.insertList(4);
   List.insertList(1);
   List.trverList();
   return 0;
}



先创造出对象来,再 List.xxxx()  用成员变量、函数!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值