Leetcode 206. Reverse Linked List 递归反转链表以及循环的优雅不优雅解法

  • 递归的方法反转整个链表
    • 其中,head->next->next = head 表示已经被逆转好的链表的最后一个元素的下一位,连到当前元素上

递归

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head || !head->next) return head;
        ListNode* last = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return last;
    }
};

循环

  • 循环方法显然避免了栈调用的过程
  • 值得注意的是循环体内部,几个指针移动的顺序。显然code2更优雅许多倍

code1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==nullptr) return NULL;
        ListNode* dummy = NULL;
        ListNode* pre = dummy;
        ListNode* cur = head;
        ListNode* post= head->next;
        while(cur!=NULL){
             cur->next = pre;
             pre = cur;
             cur = post; 
             if(post) post=post->next; // 最后一次,post会指向 null->next 此时会报错,因此用循环判断下
        }
        return pre; 
    }
};

code2

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = NULL;
        ListNode* cur =  head;
        if(cur == NULL)
            return  NULL;
        ListNode* next;

        while(cur!=NULL){
            next = cur->next; // 先把下一个点存起来
            cur->next = pre; // 当前点指向上一个点,反转
            pre = cur; // 上一个点的指针移动到当前节点上
            cur = next; // 当前节点后移
        }

        return pre;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值