首先想到是改变链表结构,使其从尾指向头
逆序链表:
ListNode* ListReverse(ListNode *head){
if(head==NULL||head->next==NULL) return head;
ListNode *p->next=head;
ListNode *current,*pre=head;
current=pre->next;
while(current){
pre->next=current->next;
current->next=p->next;
p->next=current;
current=pre->next;
}
return p->next;
}
从头到尾打印链表,意味着先进后出,所以可以使用栈结构
vector<int> ListReverse(ListNode *head){
std::stack<ListNode*> s;
vector<int> res;
if(head==NULL) return res;
ListNode *p=head;
if(p!=NULL){
s.push(p);
p=p->next;
}
while(!s.empty()){
p=s.top();
res.push_back(p->val);
s.pop();
}
return res;}
既然想到了用栈来实现,而递归本质上也是一种栈
vector<int> ListReverse(ListNode *head){
vector<int> res;
if(head==NULL) return res;
ListNode *p=head;
if(p){
if(p->next)
ListReverse(p->next);
res.push_back(p->val);
}
return res;
}