这道题是一道基础题目,运用递归比较直观,运用迭代比较节约资源。
方法1递归:
对于每一个链表头,对它的next节点链接的链表进行翻转,调用reverse(head->next)就能在递归之后得到一个翻转过的链表,此时将原头节点插入反转过后的尾节点即可。
ListNode* reverseList(ListNode* head) {
if(head!=nullptr&&head->next!=nullptr)
{
ListNode* now=head;
ListNode* temp=reverseList(head->next);
now->next=nullptr;
head=temp;
while(temp->next!=nullptr)
temp=temp->next;
temp->next=now;
return head;
}
return head;
}
方法2迭代:
相对递归而言不算直观,思路基本上是将当前节点的下一个节点移动到当前节点的前面,直到当前节点next域为空。
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr)
return head;
ListNode* truehead=head;
while(head->next!=nullptr)
{ListNode*temp=head;
temp=temp->next;
head->next=temp->next;
temp->next=truehead;
truehead=temp;}
return truehead;
}