//迭代
ListNode* reverseList(ListNode* head) {
if(head == nullptr) return head;
stack<ListNode*> s;
ListNode *p = head;
while(p->next){
s.push(p);
cout<<p->val<<" ";
p = p->next;
}
head = p;
// ListNode *q = p;
cout<<endl<<head->val<<endl;
while(!s.empty()){
p->next = s.top();s.pop();
p = p->next;
}
p->next = nullptr; //这句非常重要错过很多次了。
return head;
}
//递归
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr){
return head;
}
ListNode *tmp = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return tmp;
}
反转链表的递归和非递归写法
最新推荐文章于 2023-07-08 21:56:43 发布