从头到尾遍历的时候已经可以取出节点值,想要倒序打印,只需要将节点存储以后再反序输出。
可以用栈实现,这里提供的是vector迭代器取出的实现方法。
#include <iostream>
using namespace std;
//
struct ListNode
{
int data;
ListNode* pnext;
};
//
void addtotail(ListNode** pHead, int value)
{
ListNode* pNew = new ListNode();
pNew->data = value;
pNew->pnext = NULL;
if (*pHead == NULL)
{
*pHead = pNew;
}
else
{
ListNode* pNode = *pHead;
while (pNode->pnext != NULL)
pNode = pNode->pnext;
pNode->pnext = pNew;
}
}
//
void removenode(ListNode** pHead, int value)
{
if (*pHead == NULL)
return;
ListNode *pNode = *pHead;
if (pNode->data == value)
{
*pHead = pNode->pnext;
return;
}
while (pNode->pnext != NULL) {
if (pNode->pnext->data == value) {
pNode->pnext = pNode->pnext->pnext;
delete pNode->pnext;
return;
}
pNode = pNode->pnext;
}
}
//
#include<vector>
void printListreversely(ListNode *Head)
{
if (Head == NULL)
return;
ListNode* pNode = Head;
vector<int> vi = {};
while (pNode != NULL)
{
vi.push_back(pNode->data);
pNode = pNode->pnext;
}
for (auto iter = vi.end()-1; iter != vi.begin(); iter--) {
cout << *iter << endl;
}
cout << vi[0] << endl;
}
//
#include<stack>
void zhan(ListNode* Head)
{
stack<ListNode*> nodes;
ListNode* pnode = Head;
while (pnode != NULL)
{
nodes.push(pnode);
pnode = pnode->pnext;
}
while (!nodes.empty())
{
pnode = nodes.top();
cout << pnode->data << endl;
nodes.pop();
}
}
//
void digui(ListNode *Head)
{
if (Head == NULL)
return;
ListNode* pnode = Head;
if (pnode->pnext != NULL)
{
digui(pnode->pnext);
}
cout << pnode->data << endl;
}
int main()
{
ListNode* p = NULL;
addtotail(&p, 1);
addtotail(&p, 1);
addtotail(&p, 2);
addtotail(&p, 3);
removenode(&p, 1);
digui(p);
return 0;
}