c++,双向链表实现尾插。别用STL的list。 void list::insert_back(int Adata);
1个回答
展开全部
// 节点类
template<class T>
struct MyNode
{
MyNode() { m_pPriv = nullptr; m_pNext = nullptr; }
T m_stValue;
MyNode *m_pPriv;
MyNode *m_pNext;
};
template<class T>
class MyList
{
public:
MyList(const MyList &st) = delete;
MyList& operator= (const MyList &st) = delete;
MyList()
{
m_pHead = nullptr;
m_pTail = nullptr;
}
~MyList() { Clear(); }
// 队尾插入元素
void Insert_Back(const T &stValue)
{
MyNode<T> *pNode = new MyNode<T>;
assert(nullptr != pNode);
pNode->m_stValue = stValue;
// 第一个元素
if (nullptr == m_pHead)
{
m_pHead = pNode;
m_pTail = pNode;
}
else
{
// 当前队尾的下一节点必为空
assert(nullptr != m_pTail && nullptr == m_pTail->m_pNext);
m_pTail->m_pNext = pNode;
pNode->m_pPriv = m_pTail;
m_pTail = pNode;
}
}
// 输出测试
void Print()
{
MyNode<T> *pCurrent = m_pHead;
while (nullptr != pCurrent)
{
cout << pCurrent->m_stValue << "; ";
pCurrent = pCurrent->m_pNext;
}
cout << endl;
}
// 清空链表
void Clear()
{
MyNode<T> *pCurrent = m_pHead;
while (nullptr != pCurrent)
{
m_pHead = m_pHead->m_pNext;
delete pCurrent;
pCurrent = m_pHead;
}
m_pHead = nullptr;
m_pTail = nullptr;
}
private:
MyNode<T> *m_pHead; // 指向表头的指针
MyNode<T> *m_pTail; // 指向表尾的指针
};
template<class T>
struct MyNode
{
MyNode() { m_pPriv = nullptr; m_pNext = nullptr; }
T m_stValue;
MyNode *m_pPriv;
MyNode *m_pNext;
};
template<class T>
class MyList
{
public:
MyList(const MyList &st) = delete;
MyList& operator= (const MyList &st) = delete;
MyList()
{
m_pHead = nullptr;
m_pTail = nullptr;
}
~MyList() { Clear(); }
// 队尾插入元素
void Insert_Back(const T &stValue)
{
MyNode<T> *pNode = new MyNode<T>;
assert(nullptr != pNode);
pNode->m_stValue = stValue;
// 第一个元素
if (nullptr == m_pHead)
{
m_pHead = pNode;
m_pTail = pNode;
}
else
{
// 当前队尾的下一节点必为空
assert(nullptr != m_pTail && nullptr == m_pTail->m_pNext);
m_pTail->m_pNext = pNode;
pNode->m_pPriv = m_pTail;
m_pTail = pNode;
}
}
// 输出测试
void Print()
{
MyNode<T> *pCurrent = m_pHead;
while (nullptr != pCurrent)
{
cout << pCurrent->m_stValue << "; ";
pCurrent = pCurrent->m_pNext;
}
cout << endl;
}
// 清空链表
void Clear()
{
MyNode<T> *pCurrent = m_pHead;
while (nullptr != pCurrent)
{
m_pHead = m_pHead->m_pNext;
delete pCurrent;
pCurrent = m_pHead;
}
m_pHead = nullptr;
m_pTail = nullptr;
}
private:
MyNode<T> *m_pHead; // 指向表头的指针
MyNode<T> *m_pTail; // 指向表尾的指针
};
追问
写的什么乱七八糟的。
追答
一开始没看懂你那个void list::insert_back(int Adata);是代表值为int,所以写的模板类,用int类型实例化MyList,点右下角的"“展开”之后排版会好看一点
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询