节点定义
typedef struct MyNode{
int data;
struct MyNode* next;
MyNode():dsta(0),next(NULL){}
MyNode(int val):data(val),next(NULL){}
}Node;
类定义
class MyList{
public:
MyList();
MyList(int val);
MyList(MyList& list);
~MyList();
bool isEmpty();
void Reverse();
size_t Length();
void clear();
void print();
void inserthead(int val);
void inserttail(int val)
/*
friend ostream& operator<<(ostream& it,MyList& list){
if(list.head==NULL){
it<<"链表为空";
return it;
}
Node* temp = list.head;
while (temp != nullptr) {
it << temp->data << " ";
temp = temp->next;
}
return it;
}
*/
private:
Node* head;
size_t length1;
};
类的实现
MyList::MyList(){
head=NULL;
length1=0;
}
MyList::MyList(int val){
Node*temp=new Node(val);
head=temp;
length1=1;
}
MyList::MyList(MyList& list){
head = NULL;
Node* temp = list.head;
while(temp!=NULL){
inserttail(temp->data);
temp = temp->next;
}
}
MyList::~MyList(){
clear();
}
MyList::length(){
return length1;
}
bool MyList::isEmpty(){
if(head==NULL){
return true;
}
return false;
}
void MyList::Reverse(){
if (length1 == 0) {
return;
}
if (length1 == 1) {
return;
}
Node* list1 = NULL;
Node* temp = head;
while (temp!=NULL) {
Node* first = temp;
Node* middle = first->next;
if (list1 == NULL) {
list1 = first;
list1->next = NULL;
}
else {
first->next = list1;
list1 = first;
}
temp = middle;
}
head = list1;
}
void MyList::clear(){
Node* temp = head;
while(temp!=nullptr){
Node* curr = temp;
Node* currnext = temp->next;
delete curr;
temp = currnext;
}
head = nullptr;
length1 = 0;
}
void MyList::inserthead(int val){
Node* temp = new Node(val);
if (head == NULL) {
head = temp;
length1 = 1;
return;
}
Node* temp2 = head;
temp->next = temp2;
head = temp;
length1++;
}
void MyList::inserttail(int val){
Node* temp = head;
if (temp == NULL) {
head = new Node(val);
length1 = 1;
return;
}
while (temp->next != NULL) {
temp = temp->next;
}
Node* temp2 = new Node(val);
temp->next = temp2;
length1++;
}
void MyList::print(){
if (length1 == 0) {
cout << "链表为空" << endl;
return;
}
Node* temp = head;
while (temp!=nullptr) {
Node* curr = temp;
Node* currnext = temp->next;
cout << curr->data << " ";
temp = currnext;
}
cout<<endl;
}
类的测试
#include"MyList.h"
int main() {
cout << "对空链表进行操作1:" << endl;
MyList list1;
cout << " "<<list1<<endl;
cout << " 链表的长度: "<<list1.length() << endl;
cout << " 链表插入 1 2 3 4 5 " << endl;
for (int i = 1; i <= 5; i++) {
list1.inserttail(i);
}
cout << " 链表的打印" << endl;
cout << " ";
list1.print();
cout << " 链表添加头结点0" << endl;
list1.inserthead(0);
cout << " "<<list1 << endl;
cout << "对非空链表进行操作2:" << endl;
MyList list2(2);
cout<<" 链表的长度:"<<list2.length()<<endl;
cout << " "<<list2 << endl;
for (int i = 3; i <= 10; i++) {
list2.inserttail(i);
}
cout << "链表的复制构造3:" << endl;
MyList list3(list2);
cout << " 链表的长度:" << list3.length() << endl;
cout << " "<<list3 << endl;
cout << " 删除list3的节点4" << endl;
list3.lisdel(4);
cout << " "<<list3 << endl;
getchar();
return 0;
}
测试验证截图
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/d2caa3283eb6a8b3ad27fc08975f2b09.jpeg)