剑指offer——从尾到头打印链表

题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值。

说实话,我最开始的思路是,定义一个辅助数组,将这个链表的值依次存入到数组中去,压根就没打算用栈这个数据结构的。我感觉两个效率差不多吧。有想法的通知麻烦指出来。

算法实现

#include <iostream>
#include<stack>
using namespace std;

struct Node
{
    int val;
    Node * next;
};

struct List
{
    Node * head;
    int size;
};

void initList(List * list)
{
    list->head = new Node();
    list->size = 0;
}

void addList(List * list, int array[], int len)
{
    int i;
    Node * p = list->head;
    for (i = 0; i < len; i++)
    {
        Node * temp = new Node();
        temp->next = NULL;
        temp->val = array[i];
        p->next = temp;
        p = temp;
        list->size++;
    }
}
//倒序输出
void DaoXuShuChu(List list)
{
    Node * pHead = list.head;
    if (pHead->next == NULL && list.size == 0)
    {
        cout << "链表为空" << endl;
        return;
    }

    int length = list.size;
    int i = length;
    int * pValue = new int[length];

    Node * p = pHead->next;     //让p指向链表第一个元素

    while (p != NULL)
    {
        pValue[--i] = p->val;
        p = p->next;
    }

    for (int j = 0; j < length; j++)
        cout << pValue[j] << endl;

}

//倒序输出1
void DaoXuShuChu1(List list)
{
    Node * pHead = list.head;
    if (pHead->next == NULL && list.size==0)
    {
        cout << "链表为空" << endl;
        return;
    }

    stack<int> ss;

    Node * p = pHead->next;     //让p指向链表第一个元素

    while (p!=NULL)
    {
        ss.push(p->val);
        p = p->next;
    }

    //返回在堆栈中元素数目
    int n = ss.size();
    for (int i = 0; i < n; i++)
    {
        cout << ss.top() << endl;
        ss.pop();
    }
}

//倒序输出2
void DaoXuShuChu2(List list)
{
    Node * pHead = list.head;
    if (pHead->next == NULL && list.size == 0)
    {
        cout << "链表为空" << endl;
        return;
    }
    //知识改变了栈结构中存储的数据类型而已,根本就算不上另外一种。
    stack<Node*> ss;

    Node * p = pHead->next;     //让p指向链表第一个元素

    while (p != NULL)
    {
        ss.push(p);
        p = p->next;
    }

    //返回在堆栈中元素数目
    int n = ss.size();
    for (int i = 0; i < n; i++)
    {
        cout << (ss.top())->val << endl;
        ss.pop();
    }
}
//倒序输出3
//采用递归也可以实现。我就没写了,有兴趣的人可以试试

int main()
{
    List list;
    initList(&list);

    int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    addList(&list, array, 10);

    DaoXuShuChu(list);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值