首先是Node.h
#pragma once
#include<iostream>
using namespace std;
class Node
{
public:
Node()
{
data = 0;
next = NULL;
};
Node * next;
int data;
};
然後是LinkList.h
#pragma once
#include<iostream>
#include"Node.h"
using namespace std;
class LinkList
{
public:
LinkList();
~LinkList();
void CreatLinkList(int l);
void Print();
private:
int length=0;
Node * head,*tail;
};
LinkList::LinkList()
{
head = new Node;
tail = head;
length++;
}
LinkList::~LinkList()
{
Node* temp;
int i = 0;
while (head!=NULL)
{
temp = head;
head = head->next;
delete temp;
i++;
}
}
void LinkList::CreatLinkList(int l)
{
length = l;
if (length == 0)
{
cout << "Failed to Creat!"<<endl;
}
else
{
head->next = new Node;
tail = head->next;
cout << "Input the data of this node: ";
cin >> tail->data;
for (int i = 1; i < length; i++)
{
tail->next = new Node;
tail = tail->next;
cout<< "Input the data of this node: ";
cin >> tail->data;
tail->next = NULL;
}
}
}
void LinkList::Print()
{
if (length == 0)
{
cout << "Empty list;"<<endl;
}
else
{
Node * p=head->next;
while (p != NULL)
{
cout << p->data << endl;
p = p->next;
}
}
}
最後在 LinkList.cpp中測試
#pragma once
#include<iostream>
#include"Node.h"
#include"LinkList.h"
using namespace std;
int main()
{
LinkList L;
L.CreatLinkList(5);
L.Print();
}