题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
C++实现:
思想:入栈然后出栈即为逆序
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { ListNode *p = head; vector<int> v; stack<int> s; while(p){ s.push(p->val); p = p->next; } while(!s.empty()){ v.push_back(s.top()); s.pop(); } return v; } };
C++实现:
利用C++ 的reverse函数直接实现逆置
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { ListNode *p = head; vector<int> v; while(p){ v.push_back(p->val); p = p->next; } reverse(v.begin(), v.end()); return v; } };
java实现:
链表头插法实现原地逆置,要注意判空,否则会报空指针异常
/** * public class ListNode { * int val; * ListNode next = null; * * ListNode(int val) { * this.val = val; * } * } * */ import java.util.ArrayList; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> list = new ArrayList<>(); if(listNode==null) return list; ListNode L = listNode; ListNode nextL = L.next; ListNode newList = new ListNode(0); newList.next = L; L.next = null; while(nextL != null){ L = nextL; nextL = nextL.next; L.next = newList.next; newList.next = L; } ListNode p = newList.next; while(p != null){ list.add(p.val); p = p.next; } return list; } }