(编程小白,欢迎大家一起探讨)
1.使用容器栈
ListNode* reverseList(ListNode* head) {
if(head==NULL) return head;
stack<ListNode*> s;
ListNode* p=head;
while(p!=NULL)
{
s.push(p);
p=p->next;
}
head=p=s.top();
s.pop();
while(!s.empty())
{
p->next=s.top();
s.pop();
p=p->next;
}
p->next=NULL;
return head;
}
2.迭代
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* p1 = NULL;
ListNode* p2 = head;
while (p2!= NULL)
{
ListNode* temp = p2->next;
p2->next = p1;
p1 = p2;
p2 = temp;
}
return p1;
}
3.递归
ListNode* reverseList(ListNode* head) {
if (head==NULL || head->next==NULL) return head;
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}