从尾到头打印单向链表

点:抽象问题简化问题


题意:单链表,从尾到头打印

如原始链表:0 1 2 3 4 5 6 7 8 9

则应该打印:9 8 7 6 5 4 3 2 1 0


思路:如果做链表逆序,会破坏原始链表。这是应该倒过来想。

    递归、栈,是倒过来想的常用伎俩,是解决很多面试题的思路。

    本题的方案就是:顺序遍历一次,把每个节点值依次入栈,可以显示用栈也可以递归,最好是显示入栈,然后再挨个出栈打印就行。


代码:

#include <iostream>
#include <stack>


template<class T> struct Node {
    T val;
    Node *next;
    Node(T _val):val(_val), next(nullptr) {}
};

template<class T> class Slist {
    Node<T> *root;

public:
    Slist():root(nullptr) {}
    ~Slist () {
        Node<T> *cur = root;
        while (cur) {
            Node<T> *next = cur->next;
            delete cur;
            cur = next;
        }
    }

    void Add (T val) {
        if (!root) {
            root = new Node<T>(val);
        } else {
            Node<T> *cur = root;
            while (cur) {
                if (cur->next) {
                    cur = cur->next;
                } else {
                    cur->next = new Node<T>(val);
                    break;
                }
            }
        }
    }

    void Show () {
        Node<T> *cur = root;
        while (cur) {
            std::cout << cur->val << "\t";
            cur = cur->next;
        }
        std::cout << std::endl;
    }
    
    void Reverse_Show () {
        std::stack<T> stk;
        Node<T> *cur = root;
        while (cur) {
            stk.push(cur->val);
            cur = cur->next;
        }
        while (!stk.empty()) {
            T v = stk.top();
            stk.pop();
            std::cout << v << "\t";
        }
        std::cout << std::endl;
    }
};

int main () {
    Slist<int> sl;
    for (int i = 0; i < 10; i++) {
        sl.Add(i);
    }
    sl.Show();
    sl.Reverse_Show();
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值