链表数据翻转输出

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

/*
 * 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
 *
 * 思路:
 *      1、将链表中每个结点的值压入栈中
 *      2、从栈中依次取出栈顶元素并写入整型数组中
 *
 *
 *     输入:
 *      ListNode 类型链表 0 1 2 3
 *     输出:
 *      vector<int> result is 3210
 */

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

// 声明结构体
struct Node{
    int val;
    struct Node * next;
    Node(int i) :
        val(i),next(NULL){
    }
};



//输入一个Node链表,输出一个数据翻转的数组
vector<int> printListFromTailToHead(Node* head){
        struct Node *pNode = head;
        vector<int> node_list;
        stack<int> stack_list;
        while (pNode!=NULL){
           stack_list.push(pNode->val);
           pNode = pNode->next;
        }
       while(!stack_list.empty()){
          node_list.push_back(stack_list.top());
          stack_list.pop();
       }

    return node_list;

}

int main(){
    struct Node *node_list,*head,*temp;
    struct Node node(0);
    head = &node;
    temp = node_list = head;
//构造Node链表
    for (int i = 1; i < 4 ; ++i) {
            temp = new Node(i);
            node_list->next = temp;
            node_list = node_list->next;
    }
    vector<int> result = printListFromTailToHead(head);
    cout << "vector<int> result is " ;
    for (int j = 0; j < result.size() ; ++j) {
       cout << result[j];
    }
    cout << endl;

}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值