思路
看到这道题的第一思路就是用栈。
于是我写了下面的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<>(); ArrayList<Integer> list = new ArrayList<>(); while (listNode != null) { stack.push(listNode.val); listNode = listNode.next; } while (!stack.empty()) { list.add(stack.pop()); } return list; } }
后来又想起来了之前做过的一道链表反转的题目,其实这道题也是链表反转,于是我写了这样一段代码:
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> ret; ListNode* temp = NULL; ListNode* newHead = NULL; while (head) { temp = head; head = head->next; temp->next = newHead; newHead = temp; } while (newHead) { ret.push_back(newHead->val); newHead = newHead->next; } return ret; } };
另外还有一种解法就是利用std的reverse:
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> ret; while (head) { ret.push_back(head->val); head = head->next; } std::reverse(ret.begin(), ret.end()); return ret; } };