输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
C++版本
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
int i = 0;
ListNode *p = head;
while (p) {
++i;
p = p->next;
}
vector<int> array(i,0);
p = head;
while (p && i) {
--i;
array[i] = p->val;
p = p->next;
}
return array;
}
};
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector <int> result;
if(head==NULL) {
return result;
}
stack<ListNode*> reverse;
ListNode* p = head;
while(node != NULL) {
reverse.push(p);
p = p->next;
}
while(!reverse.empty()) {
p=reverse.top();
result.push_back(p->val);
reverse.pop();
}
return result;
}
};
Java版本
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if (listNode == null) {
return new ArrayList<Integer>();
} else {
ArrayList<Integer> array = printListFromTailToHead(listNode.next);
array.add(listNode.val);
return array;
}
}
}