剑指offer 06. 从头到尾打印链表
题目描述: 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
方法一: 遍历链表, 元素存放在数组中, 最后倒转数组
vector<int> reversePrint(ListNode* head) {
// 方法一: 遍历链表, 元素存放在数组中, 最后倒转数组
vector<int> v1;
while(head != nullptr){
v1.push_back(head->val);
head = head->next;
}
vector<int> res(v1.rbegin(), v1.rend());
return res;
}
方法二: 递归
void moth(ListNode* head, vector<int>& res) {
if (head == nullptr)
return;
moth(head->next, res);
res.push_back(head->val);
}
vector<int> reversePrint(ListNode* head) {
// 方法二: 递归
vector<int> res;
moth(head, res);
return res;
}
方法三: 栈 (利用先入后出的特性) 感觉和方法一差不多, 只是方法一最后的倒转是用构造函数实现的
vector<int> reversePrint(ListNode* head) {
// 方法三: 栈 (陷入后出的特性) 感觉和方法一差不多, 只是方法一最后的倒转是用构造函数实现的
stack<int> s1;
vector<int> res;
while(head){
s1.push(head->val);
head = head->next;
}
while(!s1.empty()){
res.push_back(s1.top());
s1.pop();
}
return res;
}
方法四: 利用vector的insert实现, 每次向首部插入元素
vector<int> reversePrint(ListNode* head) {
// 方法四: 利用vector的insert实现, 每次向首部插入元素
vector<int> res;
while (head) {
res.insert(res.begin(), head->val);
head = head->next;
}
return res;
}