题目链接:点击打开链接
题目大意:略。
解题思路:略。
相关企业
- 字节跳动
AC 代码
- Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ // 解决方案(1) class Solution { public int[] reversePrint(ListNode head) { int i = 0; ListNode p = head; while (null != p) { p = p.next; i++; } int[] arr = new int[i]; while (null != head) { arr[--i] = head.val; head = head.next; } return arr; } } // 解决方案(2) class Solution { ArrayList<Integer> tmp = new ArrayList<Integer>(); public int[] reversePrint(ListNode head) { recur(head); int[] res = new int[tmp.size()]; for(int i = 0; i < res.length; i++) res[i] = tmp.get(i); return res; } void recur(ListNode head) { if(head == null) return; recur(head.next); tmp.add(head.val); } } // 解决方案(3) class Solution { public int[] reversePrint(ListNode head) { LinkedList<Integer> stack = new LinkedList<Integer>(); while(head != null) { stack.addLast(head.val); head = head.next; } int[] res = new int[stack.size()]; for(int i = 0; i < res.length; i++) res[i] = stack.removeLast(); return res; } }C++
- C++
// 解决方案(1) class Solution { public: vector<int> reversePrint(ListNode* head) { recur(head); return res; } private: vector<int> res; void recur(ListNode* head) { if(head == nullptr) return; recur(head->next); res.push_back(head->val); } }; // 解决方案(2) class Solution { public: vector<int> reversePrint(ListNode* head) { stack<int> stk; while(head != nullptr) { stk.push(head->val); head = head->next; } vector<int> res; while(!stk.empty()) { res.push_back(stk.top()); stk.pop(); } return res; } };