leetcode 206 反转链表 Reverse Linked List

大兔子大兔子 提交于 2020-11-29 06:00:47

 

C++解法一:迭代法,使用前驱指针pre,当前指针cur,临时后继指针nxt;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre=NULL,*cur=head;
        while(cur!=NULL){
            ListNode* nxt=cur->next;
            cur->next=pre;
            pre=cur;cur=nxt;
        }
        return pre;
    }
};

 

C++方法二:递归法,Space:O(n),Time O(n)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
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;
    }
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!