算法知識視頻講解算法
連接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035 來源:牛客網 class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> value; ListNode *p=NULL; p=head; stack<int> stk; while(p!=NULL){ stk.push(p->val); p=p->next; } while(!stk.empty()){ value.push_back(stk.top()); stk.pop(); } return value; } };
2. 數組翻轉:數組翻轉能夠用C++自帶的函數,也能夠本身實現數組
class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> value; ListNode *p=NULL; p=head; while(p!=NULL){ value.push_back(p->val); p=p->next; } //reverse(value.begin(),value.end()); //C++自帶的翻轉函數 int temp=0; int i=0,j=value.size()-1; while(i<j){ temp=value[i]; //也能夠用swap函數,swap(value[i],value[j]); value[i]=value[j]; value[j]=temp; i++; j--; } return value; } };
class Solution { public: vector<int> value; vector<int> printListFromTailToHead(ListNode* head) { ListNode *p=NULL; p=head; if(p!=NULL){ if(p->next!=NULL){ printListFromTailToHead(p->next); } value.push_back(p->val); } return value; } };
4. 使用反向迭代器ide
連接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035 來源:牛客網 class Solution { public: vector<int> printListFromTailToHead(struct ListNode* head) { vector<int> v; ListNode *p = head; while (p != nullptr) { v.push_back(p->val); p = p->next; } //反向迭代器建立臨時對象 return vector<int>(v.rbegin(), v.rend()); } };