杂
长时间使用比较高级的语法,较与链表这种基本操作也只是略知。虽然是基本操作,但是code时还是出现了错误。最终还是那句话,脑子不够强大,链表还是要手画。
code
class MyNode {
public:
int data;
MyNode *next;
MyNode(int _data) { data = _data; next = nullptr; }
};
class NodeList
{
public:
NodeList();
~NodeList();
// 头插
void insertNode(int data);
// 打印
void showList();
// 反转
void turnList();
// 删除元素
void delData(int data);
// 查找
bool findData(int data);
// 全删
void delAll();
// 长度
int getLen();
private:
int m_iLen;
MyNode *pHead;
};
NodeList::NodeList()
{
pHead = new MyNode(-1);
m_iLen = 0;
}
NodeList::~NodeList()
{
delAll();
delete pHead;
pHead = nullptr;
}
void NodeList::insertNode(int data)
{
MyNode *p = new MyNode(data);
MyNode *temp = pHead;
while (temp->next)
{
temp = temp->next;
}
temp->next = p;
m_iLen++;
}
void NodeList::showList()
{
MyNode *temp = pHead;
while (temp->next)
{
temp = temp->next;
std::cout << temp->data << std::endl;
}
}
void NodeList::turnList()
{
MyNode *prev = pHead->next;
if (!prev)
return;
MyNode *pCur = prev->next;
while (pCur){
// 3 断 头插
prev->next = pCur->next;
pCur->next = pHead->next;
pHead->next = pCur;
// 更新当前节点
pCur = prev->next;
}
}
void NodeList::delData(int data)
{
MyNode *temp = pHead;
while (temp->next)
{
MyNode *p = temp->next;
if (p->data == data) {
temp->next = p->next;
p->next = nullptr;
delete p;
p = nullptr;
break;
}
temp = temp->next;
}
}
bool NodeList::findData(int data)
{
bool ret = false;
MyNode *temp = pHead;
while (temp->next)
{
MyNode *p = temp->next;
if (p->data == data) {
std::cout << "find data" << std::endl;
ret = true;
break;
}
temp = temp->next;
}
return ret;
}
void NodeList::delAll()
{
MyNode *temp = pHead->next;
while(temp){
MyNode *p = temp;
temp = temp->next;
p->next = nullptr;
delete p;
p = nullptr;
}
pHead->next = nullptr;
}
int NodeList::getLen()
{
return m_iLen;
}