输入一个链表,从尾到头打印链表每个节点的值。

网上搜到了两种方式,但是都没有完整可以一键运行的代码。下面提供代码给像我一样的菜鸟学习。

第一种方法:利用stack 先遍历链表,将链表节点的指针存入stack中,再依次将这些指针出栈,将指针对应的数值存入数组中。完整代码如下:

// staticTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
#include <stack>
#include <iostream>
#include <stdio.h>  
#include <stdlib.h>

using namespace std;

 struct ListNode {
       int val;
       struct ListNode *next;
       ListNode(int x) :
             val(x), next(NULL) {
       }
 };

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> list;
		stack<struct ListNode*> nodes;
		//cout << "下面是原链表数据,从头到尾" << endl;
        while(head != NULL)
        {
			cout << head->val << " ";
            nodes.push(head);
            head = head->next; 
        }
		cout << endl;
		struct ListNode* pTop = head;
		while(!nodes.empty()){
			pTop = nodes.top();
			list.push_back(pTop->val);
			nodes.pop();
		}
        //reverse(list.begin(),list.end());       //reverse()函数用于反转vector数组   
        return list;
    }
};
void printintVector(vector<int>  &vt ){
	
	vector<int>::iterator it = vt.begin();
	cout << "下面是链表数据的翻转,翻转为从尾到头" << endl;
	for(;it != vt.end();it++ ){
	 cout << *it << " ";
	}
	cout << endl;
}
struct ListNode* creatList(int n){
	struct ListNode* head;
	head=NULL;
	for(int i = 0; i < n; i++){
		struct ListNode *t = (struct ListNode*)malloc(sizeof(struct ListNode));
		t->val = i;
		if(head == NULL){
		  head = t;
		  head->next = NULL;
		}
		else{
			t->next = head;
			head = t;
		}
	}
    return head;
}
int _tmain(int argc, _TCHAR* argv[])
{
	struct ListNode *head;
	head = creatList(19);

	Solution s;
	vector<int> result;
	result = s.printListFromTailToHead(head);
    printintVector(result);
	system("pause");
    return 0;  
}
第二种方法是将链表中的数据依次存入vector中,再利用reverse函数反转vector。核心代码如下

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> list;
		stack<struct ListNode*> nodes;
		//cout << "下面是原链表数据,从头到尾" << endl;
        while(head != NULL)
        {
			cout << head->val << " ";
			list.push_back(head->val);
            head = head->next; 
        }
		cout << endl;

        reverse(list.begin(),list.end());       //reverse()函数用于反转vector数组   
        return list;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值