Print the linked list in reverse order

The first method uses vector, the time complexity and space complexity are O(N), which is relatively simple and ignored.

Method 2, using recursion, the space complexity and time complexity are also O(N).

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
	void printListFromTailToHead(ListNode* head, vector<int> &vec)
	{
		if(head == NULL) return;
		printListFromTailToHead(head->next, vec);
		vec.push_back(head->val);

	}
    vector<int> printListFromTailToHead(ListNode* head) {
    	vector<int> &vec;
        printListFromTailToHead(head, vec);
        return vec;
        
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325208798&siteId=291194637