头文件 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() 用成员变量、函数!