Print a singly linked list from end to end

Print linked list from tail to head: Enter the head node of a linked list, and print the value of each node from tail to head in turn.
The following three methods are introduced to achieve this problem.
①Directly change the direction of the pointer. This method is generally not recommended. It changes the structure of the linked list.
②Since it is printed from the end to the beginning, we can easily think of the stack. The structure of the stack is " "Last in, first out"
we can traverse the linked list first, if the current node is not empty, put it on the stack, use the stack to save the current traversed value first, until the last node of the linked list is empty, then push the stack The value saved in the output.
First define a linked list structure

struct ListNode   //定义链表结构
{
    int data;
    ListNode* pNext;
}Node;

The implementation of the function is as follows:

void PrintHeadtoTail(ListNode* pHead)
{
    std::stack<ListNode*> s;//定义一个栈来存储链表的节点
    ListNode* pNode = pHead;
    while (pNode)     //当链表不为空时,将链表节点入栈
    {
        s.push(pNode);
        pNode = pNode->pNext;
    }    //出了循环,链表遍历完成
    while (!s.empty())   //打印栈中的数据
    {
        pNode = s.top();
        printf("%d\t", pHead->data);
        s.pop();
    }

}

③Use recursive method to achieve (possibly stack) overflow

void PrintHeadtoTail(ListNode* pHead)
{
    if (pHead != NULL)
    {
        if (pHead->pNext != NULL)
        {
            PrintHeadtoTail(pHead->pNext);
        }
    }
    printf("%d\t", pHead->data);

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326432910&siteId=291194637