每天打卡一小时 第二十六天
接昨天的题
#include <iostream>
using namespace std;
template <class T>
class Node
{
private:
Node<T>* next;
public:
T data;
Node(const T& data, Node<T>* next = 0);
Node(const Node<T>& p);
~Node();
T getData();
};
template <class T>
Node<T>::Node(const T& data, Node<T>* next) : data(data), next(next)
{
cout << "Node Constructor run" << endl;
}
template <class T>
Node<T>::Node(const Node<T>& p) : data(p.data), next(p.next)
{
cout << "Node CopyConstructor run" << endl;
}
template <class T>
Node<T>::~Node()
{
cout << "Node Destructor run" << endl;
}
template <class T>
T Node<T>::getData()
{
return data;
}
template <class T>
class LinkList
{
private:
Node<T>* headNode;
Node<T>* position;
public:
LinkList() : headNode(new Node<T>()), position(headNode)
{
cout << "LinkList Constructor run" << endl;
}
LinkList(const T arr[], int n) : headNode(new Node<T>()), position(headNode)
{
cout << "LinkList Constructor run" << endl;
for (int i = n - 1; i >= 0; --i) {
position->next = new Node<T>(arr[i], position->next);
}
}
LinkList(const LinkList<T>& other) : headNode(other.headNode), position(other.position)
{
cout << "LinkList CopyConstructor run" << endl;
}
~LinkList()
{
cout << "LinkList Destructor run" << endl;
while (headNode->next) {
Node<T>* p = headNode->next;
headNode->next = p->next;
delete p;
}
delete headNode;
}
bool searchNode(const T& value)
{
Node<T>* p = headNode->next;
while (p) {
if (p->getData() == value) {
position = p;
return true;
}
p = p->next;
}
return false;
}
int getSize()
{
int cnt = 0;
Node<T>* p = headNode->next;
while (p) {
cnt++;
p = p->next;
}
return cnt;
}
void next()
{
if (position->next) {
position = position->next;
}
}
Node<T>* currNode() const
{
return position;
}
void delNode()
{
if (!position)
return;
if (position == headNode) {
headNode = headNode->next;
delete position;
position = headNode;
} else {
Node<T>* temp = headNode;
while (temp->next != position) {
temp = temp->next;
}
temp->next = position->next;
delete position;
position = temp->next;
}
}
void insertNode(Node<T>* n)
{
const Node<T>* tmp = n;
tmp->next = position->next;
position->next = new Node<T>(*tmp);
position = position->next;
}
void show() const
{
Node<T>* temp = headNode->next;
while (temp) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}
};
int main()
{
int i,a[5]= {0,1,2,3,4};
for(i=0;i<5;i++)
scanf("%d",&a[i]);
LinkList<int> l1(a,5),l2(l1);
cout<<l2.getSize()<<endl;
l1.show();
if (l2.searchNode(2))
cout << "Found: " << l2.currNode()->getData() << endl;
else
cout<<"Not Found"<<endl;
l2.delNode();
Node <int> *p1=new Node<int>(11);
l2.insertNode(*p1);
l2.show();
return 0;
}
报错很多,修改很长时间,并没有解决问题

浙公网安备 33010602011771号