题目描述:
输入一个链表,从尾到头打印链表每个节点的值。
思路:
顺序访问链表,存入栈中,然后输出
栈中元素。
代码:
C++:
/**
* 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;
stack<int> stack;
if(head == NULL) return result;
ListNode* p = head;
while(p != NULL){
stack.push(p->val);
p = p->next;
}
while(!stack.empty()){
result.push_back(stack.top());
stack.pop();
}
return result;
}
};
JAVA:
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.isEmpty()){
res.add(stack.pop());
}
return res;
}
}