5.25

发布时间 2023-05-25 20:50:24作者: 混沌武士丞

一 题目以及要求

请使用模板参数设计实现单向链表模板类LinkList,应能根据需求构建相应类型数据结点的单向链表结构,main(void)完成对其的测试

(1)设计实现结点模板类Node,结点的数据域应能各种类型数据;其中成员函数getData(void)的作用是获取结点的数据域。构造函数输出信息“Node Constructor run”,拷贝构造函数输出信息“Node CopyConstructor run”,析构函数输出信息“Node Destructor run”
(2)在结点模板类Node的支持下设计实现结点单向链表模板类LinkList,其中:
①LinkList类的数据包括结点链表的头结点headNode和游标position(游标用于表示当前操作位置)
②有参构造函数实现由数组构建链表的功能,构造函数输出信息“LinkList Constructor run”;拷贝构造函数输出信息“LinkList CopyConstructor run”,析构函数输出信息“LinkList Destructor run”
③设计实现成员函数insertNode(n),其功能为在游标位置后插入一个同类型结点n。
④设计实现成员函数searchNode(value),其功能为在链表中查找数据域等于value的结点,若查找成功的同时修改游标位置。
⑤设计实现成员函数getSize(),其功能为返回链表中的元素个数。
⑥设计实现成员函数next(),其功能为使游标移动到下一个结点。
⑦设计实现成员函数currNode()const,其功能为返回当前结点。
⑧设计实现成员函数delNode(),其功能为移除当前结点。
⑨设计实现成员函数show(),其功能为输出链表。

二 代码

#include <iostream>
using namespace std;

template·<typename·T>
class·Node·{
public:
Node(T·data):·data(data),·next(nullptr)·{
cout·<<·"Node·Constructor·run"·<<·endl;
}

Node(const·Node<T>&·other)·:·data(other.data),·next(other.next)
{
}

~Node()·{

}

T·getData()·{·return·data;·}
Node<T>*·getNext()·{·return·next;·}
void·setNext(Node<T>*·next)·{·this->next·=·next;·}
private:
T·data;
Node<T>*·next;
};


template·<typename·T>
class·LinkList·{
public:
LinkList():·headNode(new·Node<T>(T())),·position(headNode)·{
cout·<<·"LinkList·Constructor·run"·<<·endl;
}

LinkList(T·data[],·int·length):·headNode(new·Node<T>(T())),·position(headNode)·{
Node<T>*·currNode·=·headNode;
for·(int·i·=·0;·i·<·length;·++i)·{
currNode->setNext(new·Node<T>(data[i]));
currNode·=·currNode->getNext();
}
cout·<<·"LinkList·Constructor·run"·<<·endl;
}

LinkList(const·LinkList<T>&·other):·headNode(new·Node<T>(T())),·position(headNode)·{
Node<T>*·currNode·=·other.headNode->getNext();
while·(currNode·!=·nullptr)·{
position->setNext(new·Node<T>(*currNode));
currNode·=·currNode->getNext();
position·=·position->getNext();
}
position·=·headNode->getNext();
cout·<<·"Node·Constructor·run"·<<·endl;
cout·<<·"Node·Constructor·run"·<<·endl;
cout·<<·"Node·Constructor·run"·<<·endl;
cout·<<·"Node·Constructor·run"·<<·endl;
cout·<<·"Node·Constructor·run"·<<·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;
}