leetcode206. 反转链表

1:迭代法

假设存在链表 1 → 2 → 3 → Ø,我们想要把它改成 Ø ← 1 ← 2 ← 3。

在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    ListNode *pre=NULL;
    ListNode *curr=head;
    while(curr!=NULL)
    {
        ListNode *temp=curr->next;
        curr->next=pre;
        pre=curr;
        curr=temp;
    }
    return pre;  
    }
        
};

2 递归

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    
    if (head == NULL || head->next == NULL) return head;
    ListNode* p=reverseList(head->next);
    head->next->next=head;
    head->next=NULL;
    return p;
    }
        
};
原文地址:https://www.cnblogs.com/renzmin/p/11877186.html