单链表的最基本创建和操作
通过友元来处理私有部分
#include <iostream>
using namespace std;
#include "ThreeLetterList.h"
//通过友元类来处理私有部分
class List;
class Node//节点
{
friend class List;//友元类操作私有数据
private:
int data;//数据域
Node* link;//指针域
};
class List//链表
{
public:
void test();
void show();
private:
Node* first;//指向第一个节点
};
void List::show()//来输出这三个节点吧
{
cout << first->data << "->"
<< first->link->data << "->"
<< first->link->link->data << endl;
}
void List::test()
{
Node* f = new Node;//创建一个节点
f->data = 44;
f->link = 0;//指针指向了0
first = f;//把头指针指向这个节点
f = new Node;//重新利用这个指针再创建一个新的节点
f->data = 72;
f->link = 0;
first->link = f;//第一个节点的link指向这个节点
f = new Node;
f->data = 210;
f->link = 0;
first->link->link = f;//这样就把三个节点串起来了
}
int main()
{
List a;
a.test();
a.show();
ThreeLetterList l;
l.test();
l.show();
return 0;
}
通过类的嵌套来实现
#pragma once
//头文件改写的都写上
#ifndef THREELETTERLIST_H
#define THREELETTERLIST_H
#include<iostream>
using namespace std;
//通过嵌套类来处理私有部分
//基本都和前面那部分代码一个道理啦
class ThreeLetterList
{
//类嵌套
class ThreeLetterNode
{
public:
char data[3];
ThreeLetterNode* link;
};
public:
void test();
void show();
private:
ThreeLetterNode* first;
};
void ThreeLetterList::test()
{
ThreeLetterNode* f = new ThreeLetterNode;
f->data[0] = 'B';
f->data[1] = 'A';
f->data[2] = 'T';
f->link = 0;
first = f;
f = new ThreeLetterNode;
f->data[0] = 'C';
f->data[1] = 'A';
f->data[2] = 'T';
f->link = 0;
first->link = f;
}
void ThreeLetterList::show()
{
cout << first->data[0] << first->data[1] << first->data[2] << "->"
<< first->link->data[0] << first->link->data[1] << first->link->data[2] << endl;
}
#endif
今天的学习结束了,加油!