网上搜到了两种方式,但是都没有完整可以一键运行的代码。下面提供代码给像我一样的菜鸟学习。
第一种方法:利用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;
}
};