输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
vector的利用:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* tmp=head;
vector<int> v;
while(tmp!=NULL){
v.push_back(tmp->val);
tmp=tmp->next;
}
reverse(v.begin(),v.end());
return v;
}
};
递归:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printfRecur(ListNode* head){
vector<int> v;
//vector<int> tmp;
if(head!=NULL)
{
if(head->next!=NULL)
{
v=printfRecur(head->next);
}
v.push_back(head->val);
}
//v.push_back(tmp);
return v;
}
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v;
v=printfRecur(head);
return v;
}
};
JAVA实现:
其实也应该用递归的
import java.util.ArrayList;
public class Third {
static class ListNode{
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(listNode==null){
return list;
}
do{
list.add(listNode.val);
listNode = listNode.next;
}
while(listNode!=null);
if(list.size()==0){
return list;
}
ArrayList<Integer> result = new ArrayList<Integer>();
for(int i=list.size()-1;i>=0;i--){
result.add(list.get(i));
}
return result;
}
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
ListNode listNode1 = new ListNode(2);
listNode.next = listNode1;
System.out.println(printListFromTailToHead(listNode));
}
}