美文网首页
l1 链表从后往前遍历(两种算法,一种思想)

l1 链表从后往前遍历(两种算法,一种思想)

作者: 张霸天 | 来源:发表于2017-09-30 13:56 被阅读0次
    
    
    #include <iostream>
    #include <stack>
    
    struct ListNode
    {
        int m_nKey;
        ListNode* m_pNext;
    };
    
    void PrintListReversingly_Recursively_01(ListNode * pHead) {
        std::stack<ListNode *> nodes;
        // 使用stack的先进后出来实现
        ListNode * pNode = pHead;
        while (pNode != NULL) {
            nodes.push(pNode);
            pNode = pNode->m_pNext;
        }
        
        while (!nodes.empty()) {
            pNode = nodes.top();
            printf("%d \t ",pNode->m_nKey);
            nodes.pop();
        }
    }
    
    void PrintListReversingly_Recursively(ListNode* pHeader) {
        if (pHeader != NULL) {
            if (pHeader->m_pNext != NULL) {
                PrintListReversingly_Recursively(pHeader->m_pNext);//使用递归
            }
            printf("%d \t ",pHeader->m_nKey);
        }
    }
    
    int main() {
        ListNode * node1 = new ListNode();
        ListNode * node2 = new ListNode();
        ListNode * node3 = new ListNode();
        
        node1->m_nKey = 1;
        node1->m_pNext = node2;
        
        node2->m_nKey = 2;
        node2->m_pNext = node3;
        
        node3->m_nKey = 3;
        node3->m_pNext = NULL;
        
        PrintListReversingly_Recursively(node1);
        
        printf("\n");//换行
        
        PrintListReversingly_Recursively(node1);
        
        delete node1;
        delete node2;
        delete node3;
        return 0;
    }
    
    

    相关文章

      网友评论

          本文标题:l1 链表从后往前遍历(两种算法,一种思想)

          本文链接:https://www.haomeiwen.com/subject/rbwgextx.html