题目:反转单链表
方法:
①先将链表中的元素全部放入vector容器中,再用reverse反转容器
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;
}
};
②先反转链表,再放进容器中
注意涉及反转链表时,考虑将pre指向空,将cur指向链表的head,这样就能解决头结点反转后指向空的问题,如果是下面的第二种指法,就
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* pre=nullptr;
ListNode* cur=head;
ListNode* tmp=cur->next;
while(cur){
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
vector<int> ret;
while(pre){
ret.push_back(pre->val);
pre=pre->next;
}
return ret;
}
};
未解问题:段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* pre=head;
ListNode* cur=head->next;
ListNode* tmp;
while(cur){
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
head->next=nullptr;
vector<int> ret;
while(pre){
ret.push_back(pre->val);
pre=pre->next;
}
return ret;
}
};
③递归调用printListFromTailToHead()
相比前两种方法,递归调用所占的内存明显较小
1.递归调用函数的返回值是递归的核心
2.此处将head=head->next放到了参数中
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
if(!head) return ret;
//此处将head=head->next放到了参数中
ret = printListFromTailToHead(head->next);
ret.push_back(head->val);
return ret;
}
};