题目描述
给定一个链表,将其从尾到头打印。
输入:1->2->3->4->5->NULL
返回:[5,4,3,2,1]
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
head = ReverseList(head);
vector<int> result;
ListNode* ptr = head;
while(ptr != nullptr) {
result.push_back(ptr->val);
ptr = ptr->next;
}
return result;
}
//反转链表
ListNode* ReverseList(ListNode* head) {
ListNode* back = head;
ListNode* pre = nullptr;
while(back != nullptr && back->next != nullptr) {
pre = back->next;
back->next = pre->next;
pre->next = head;
head = pre;
}
return head;
}
};
- 方法2:顺序遍历链表,并将值保存到链表中。然后再依次从栈中弹出。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> stk;
vector<int> result;
ListNode* ptr = head;
while(ptr != nullptr) {
stk.push(ptr->val);
ptr = ptr->next;
}
while(!stk.empty()) {
result.push_back(stk.top());
stk.pop();
}
return result;
}
};
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
func(head, result);
return result;
}
void func(ListNode* head, vector<int>& result) {
if(head == nullptr)
return;
func(head->next, result);
result.push_back(head->val);
}
};