C++
class Solution{
public:
ListNode* reverseList(ListNode* head){
stack<ListNode*> s;
ListNode* temp =head;
while(temp!=NULL){
s.push(temp);
temp=temp->next;
}
ListNode* ans = new ListNode(0);
ListNode* cur=ans;
cout<<"size "<<s.size()<<endl;
while(s.size()){
temp = s.top();
cout<<temp->val<<" ";
s.pop();
cur->next = new ListNode(temp->val);
cur = cur->next;
}
return ans->next;
}
};
Python
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
cur = head
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre
本文深入探讨了链表逆序算法的两种实现方式:使用栈的递归方法与迭代法。通过C++与Python代码详细展示了如何将链表元素顺序反转,为读者提供了清晰的算法思路与实践代码。
361

被折叠的 条评论
为什么被折叠?



